// MaxValues
#define MAX_HEALTH		(100.0)
#define MAX_MAPS		(24)
#define MAX_REGION		(5)
#define MAX_MODE		(4)
#define MAX_RANK        (15)
#define MAX_KIT			(4)
#define MAX_CP			(4)
#define MAX_CPNAME      (16)
#define MAX_AVEN_TIME   (3000)
#define MAX_XPMSG_LEN   (150)
#define MAX_XPINT_LEN   (6)
#define MAX_XPMSG_LINE  (5)
#define EXP_TEXT_HIDE   (3000)
#define MAX_DIST_BONUS  (50.0)
#define MAX_DM_WEP		(300)
#define MAX_AMMO_CRATE	(50)
#define MAX_MINES		(MAX_PLAYERS*4)
#define MINE_TRIG_RAD   (3.0)
#define MAX_WEAPON		(38)
#define MAX_LOBBY_COUNT (10)
#define MAX_SPAWN_COUNT (5)
#define MAX_GEAR        (16)

#define SCORLIM_MIN		5
#define TICKLIM_MIN		5
#define FLAGLIM_MIN		1
#define FORCLIM_MIN		10

#define SCORLIM_MAX		100
#define TICKLIM_MAX		100
#define FLAGLIM_MAX		20
#define FORCLIM_MAX		300

#define MATCHTIME_MIN	0
#define MATCHTIME_MAX	30

#define MIN_DM_PLAYERS  2
#define MAX_DM_PLAYERS  16

// Modes - Binary values for file loading
#define bDM_MODE_TDM	(8)
#define bDM_MODE_AD		(4)
#define bDM_MODE_CTF	(2)
#define bDM_MODE_CQS	(1)

// Modes - Integers for script use
#define DM_MODE_TDM		(0)
#define DM_MODE_AD		(1)
#define DM_MODE_CTF 	(2)
#define DM_MODE_CQS		(3)

// Kits
#define KIT_ASSAULT		(0)
#define KIT_MEDIC		(1)
#define KIT_SNIPER		(2)
#define KIT_ENGINEER	(3)

// Keys
#define ACTION_KEY		(16)
#define EQUIPMENT_KEY   (262144)
#define GEAR_KEY       (131072)

#define TEXT_ACTION_KEY	"~k~~VEHICLE_ENTER_EXIT~"
#define TEXT_EQUIP_KEY	"~k~~GROUP_CONTROL_BWD~"
#define TEXT_GEAR_KEY	"~k~~CONVERSATION_NO~"

// Colours
#define FRIENDLY_PLAYER_VISIBLE		0x33CCFFFF
#define ENEMY_PLAYER_VISIBLE		0xFF0000FF

#define FRIENDLY_PLAYER_INVISIBLE	0x33CCFF00
#define ENEMY_PLAYER_INVISIBLE		0xFF000000

#define FRIENDLY_OBJECTIVE			0x33CCFFFF
#define ENEMY_OBJECTIVE				0xFF0000FF

// Dialog Texts
#define DIALOGTEXT_SCORLIM		"Enter the score limit below\nFirst team to reach this amount of kills wins the match.\n\n"#C_YELLOW"Between "#SCORLIM_MIN" and "#SCORLIM_MAX"."
#define DIALOGTEXT_TICKLIM		"Enter the Attackers Ticket Count\nEach time an attacking player is killed their team ticket count depletes by 1,\nwhen at 0 the match ends and Defenders win.\n\n"#C_YELLOW"Between "#TICKLIM_MIN" and "#TICKLIM_MAX"."
#define DIALOGTEXT_FLAGLIM		"Enter the CTF Flag limit below\nWhen a team captures this many flags the match ends and they win.\n\n"#C_YELLOW"Between "#FLAGLIM_MIN" and "#FLAGLIM_MAX"."
#define DIALOGTEXT_FORCLIM		"Enter the Reinforcement Ticket limit below\nEach time a player dies, their team ticket count depletes by 1,\nwhen at 0 the match ends and that team loses.\n\n"#C_YELLOW"Between "#FORCLIM_MIN" and "#FORCLIM_MAX"."
#define DIALOGTEXT_MATCHTIME	"Enter the Match Time in minutes.\n\n"#C_YELLOW"Between "#MATCHTIME_MIN" and "#MATCHTIME_MAX"."
#define DIALOGTEXT_MAXPLAYER	"Enter the Maximum players for match\n\n"#C_YELLOW"Between "#MIN_DM_PLAYERS" and "#MAX_DM_PLAYERS" and Above the Min player count."
#define DIALOGTEXT_MINPLAYER	"Enter the Minimum players for match\n\n"#C_YELLOW"Between "#MIN_DM_PLAYERS" and "#MAX_DM_PLAYERS" and Below the Max player count."


// Macros
#define TeamMsgF(%0,%1,%2,%3)	do{new _str[128];format(_str,128,%2,%3);TeamMsg(%0,%1,_str);}while(FALSE)
#define GameMsgF(%0,%1,%2)		do{new _str[128];format(_str,128,%1,%2);GameMsg(%0,_str);}while(FALSE)

#define GetPlayerHP(%0) PlayerHP[%0]


// Forwards
forward JoinLobby(playerid); // For death timer

forward ExpMsgDestroy(playerid);
forward HideMsgBox(playerid);

forward Medic_RevivePlayer(playerid, targetid);
forward Sniper_PlaceMine(playerid);
forward Engineer_Repair(playerid, vehicleid);
forward ResetKitEquip(playerid);

forward HideHitMark(playerid);
forward EndDeathmatch();



enum DM_ENUM
{
	Team,
	Kit,
	Gear,
	Streak,
	Combo,
	PreKills,
	PreDeaths,
	PreExp
}
enum (<<=1)
{
	GearUse = 1,
	PlayingDead,
	BleedingOut,
	ExpMsgShowing,
	HasFlag,
	CapturingADPoint
}
new
	pDM_Data[MAX_PLAYERS][DM_ENUM],
	bPlayerDeathmatchSettings[MAX_PLAYERS char];



new
	DMhost 	= -1,
	DMmap  	= -1,
	DMmode 	= -1,
    MapNames[MAX_MAPS][15],
	MapModes[MAX_MAPS],
	MapRegion[MAX_MAPS],
	RegionItems[MAX_MAPS],
	MapInfo_Bio[MAX_MAPS][128],
	MapInfo_Size[MAX_MAPS][14],
	MapInfo_Kit[MAX_MAPS][26],

	SelectedRegion,

	Float:PlayerHP[MAX_PLAYERS],
	Float:pSpawnPoint[MAX_PLAYERS][3],
	MapSpawnSide[2],
	Float:CustomSpawns[2][3],
	DMmode_tmp,
	WinningTeam,
	LobbyCountInt=MAX_LOBBY_COUNT,
	Float:TankHeat[MAX_PLAYERS],
	Bar:TankHeatBar[MAX_PLAYERS],
	PlayerSpectateTarget[MAX_PLAYERS],
	tick_LastKill[MAX_PLAYERS],  // Use KILLERID
	tick_LastDeath[MAX_PLAYERS], // Use PLAYERID
	LastKilled[MAX_PLAYERS],
	PlayerShotBy[MAX_PLAYERS],
	SpawnCounter=MAX_SPAWN_COUNT,

//======================Map File load variables

	Float:DMCamPos[6],
	DMweather,
	DMtime_H,
	DMtime_M,
    MapAuthor[10],
	Float:SpawnPositions[2][3],

//======================Menu Variables

	Menu:LobbyMenu,
	Menu:TeamSelect,
	Menu:KitSelect,

	RegionMenu[60],
	RegionMaps[5][100],

//======================Deathmatch Settings Variables

	bDeathmatchSettings	=0b100111011100,
	DMminP,
	DMmaxP,
	MatchTimeLimit,

	Bar:BleedoutBar[MAX_PLAYERS],
	Blood[MAX_PLAYERS],
	DownedPlayers,
	PlayerProximity[MAX_PLAYERS],
	BleedAttacker[MAX_PLAYERS],
	BleedReason[MAX_PLAYERS],

	MSU_VehicleID[2],
	bool:MSUactive[2],
	Float:GlobalMaxHP=MAX_HEALTH;

	enum (<<=1)
	{
		Hardcore=1,		// Hardcore Mode
		ArcadeMode,		// Let's you buy weapons with money gained from killing and objectives instead of ranking up and earning weapons with XP
		Vehicles,		// Vehicles On Map [only certain maps have vehicles anyway]
		InstaHS,		// Headshot Instant Kill
		Revive,			// Medics Can Revive [when a player dies he goes to bleedout mode, has 30 seconds to be revived, before 'giving up']
		FriendlyFire,	// Friendly Fire
		MobSpawnUnit,	// Mobile Spawn Unit [for conquest, a vehicle [one for each map] can be used as a spawn position on the spawn selection screen]
		EquipmentUsage,	// Allow/Disallow usage of Equipment
		GearItemUsage,	// Allow/Disallow usage of Gear
		EqualWeapons,	// Equal Weapon Sets for classes [no unlock weapons]
		TeamTalk,		// Chat is only broadcast to players on your team [/g for global chat]
		TeamBalance		// Teams can have balanced or unbalanced amounts of players
	}
	enum
	{
		g_ProxDet,
		g_Ghillie,
		g_PlayDead,
		g_G12,
		g_Sneaky,
		g_Rocket,
		g_ExtraMags,
		g_ExtraMines,
		g_FMJ,
		g_Surprise,
		g_Disguise,
		g_Night,
		g_Thermal
	}

//======================Map Related Variables
new
	DMzone,
	JamZone,
	Float:DMzoneP[4],
	TotalDMObjects=0;

//======================Gamemode Names

new const
    ModeNames[MAX_MODE][17]=
    {
	    "Team Deathmatch",
	    "Attack/Defend",
	    "Capture The Flag",
	    "Conquest"
    },

//======================Gamemode Name Abbreiviations

    ModeABVs[MAX_MODE][4]=
    {
	    "TDM",
	    "A/D",
	    "CTF",
	    "CQS"
	},

//======================Map Region Names

    RegionNames[MAX_REGION][21]=
    {
	    "City",
	    "Country",
	    "Desert",
	    "Ocean",
	    "San Andreas Original"
    },

//======================Team Names

	TeamName[3][6]=
	{
		"Raven",
		"Valor",
		"Free"
	},

//======================Kit Names

	KitName[4][9]=
	{
		"Assault",
		"Medic",
		"Sniper",
		"Engineer"
	},

//======================Gear Names

	GearName[13][19]=
	{
		"Proximity Detector",
		"Ghillie Suit",
		"Play Dead",
		"G12",
		"Sneaky",
		"Rocketman",
		"Extra Mags",
		"Extra Mines",
		"FMJ",
		"Surprise",
		"Disguise",
		"Night Vision",
		"Thermal Vision"
	},
	GearInfo[13][121]=
	{
		"The Proximity Detector alerts you when someone shoots at you and when you are within 10 meters of an enemy mine.",
		"The Ghillie suit allows you to hide in a fake bush, useful for woodland maps. Activate with Left Alt (default Walk key)",
		"This lets you 'play dead' then to recover, press the crouch button. Activated with Left Alt (default Walk key)",
		"G12 makes you lethal with the two handed shotguns, adding an extra 10 hitpoints.",
		"Allows you to be invisible on the enemy's radar at all times.",
		"Gives you an RPG with one rocket when you spawn, useful for taking out tanks or vehicles.",
		"This gives you twice the amount of ammo in your primary and secondary weapon. Does not apply to throwables.",
		"This gives you 4 mines on the sniper class instead of 2",
		"Increases bullet penetration for all weapons and adds and extra 10 hitpoints",
		"Gives the enemy an explosive surprise when they kill you...",
		"Throughout the match you will have an enemy team skin, useful unless they notice the absence of a nametag!",
		"Spawns you with night vision goggles, make picking enemies out in the dark easy, good for night based maps",
		"Spawns you with thermal vision goggles, enemies glow red when these are in use good for dark maps"
	};

//======================Score Variables

	new
		ScoreLimit  =	10,
		FlagLimit   =	5;
	enum SCORE_TYPES
	{
		Score,
		Flags,
		Ticket
	}
	new TeamScore[SCORE_TYPES][2];

//======================Text Draw Variables

	new
		Text:flash,
		Text:ScoreBox,
		Text:ScoreStatus_Winning,
		Text:ScoreStatus_Tie,
		Text:ScoreStatus_Losing,
		Text:LobbyText,
		Text:SpawnCount,
		Text:SpecialWeps[MAX_PLAYERS],
		Text:HitMark,
		Text:HealthCount[MAX_PLAYERS],
//		Text:ActionBox[MAX_PLAYERS],
		Bar:XPbar[MAX_PLAYERS];

//======================Rank Variables

new
	RankNames[MAX_RANK+1][20]=
	{
		"<UNRANKED>",
		"FNG",
		"Private",
		"Private First Class",
		"Specialist",
		"Corporal",
		"Sergeant",
		"Master Sergeant",
		"Sergeant Major",
		"Lieutenant",
		"Captain",
		"Major",
		"Colonel",
		"Lieutenant General",
		"General",
	 	"Chuck Norris"
	},

//======================Rank Name Abbreviations

	/*
	RankAbv[MAX_RANK+1][5] =
	{
		"<0>",
		"NWB",
		"FNG",
		"PVT",
		"PVT1",
		"SPC",
		"CPL",
		"SGT",
		"MSG",
		"SGM",
		"LT",
		"CPT",
		"MJR",
		"COL",
		"LTG",
		"GEN"
		"NRS"
	};
	*/

//======================Required XP Values for Ranks

	RequiredExp[MAX_RANK+1] =
	{
	    -1,		// 0
		0,		// 1
		200,	// 2
		550,	// 3
		800,	// 4
		1200,	// 5
		2000,	// 6
		4400,	// 7
		6800,	// 8
		8500,	// 9
		10900,	// 10
		13600,	// 11
		16000,	// 12
		21400,	// 13
		25800,	// 14
		300000	// 15
	},

//======================Weapon Sets for Kits [one for each of the 15 ranks]

	RankWeapons[MAX_KIT][MAX_RANK+1][6]=
	{
		{
			{22, 30, 4, 17*3,  50*3, 1},	//	Rank 1
			{22, 30, 4, 17*4,  50*3, 1},	//	Rank 2
			{22, 30, 4, 17*5,  50*3, 1},	//	Rank 3
			{23, 30, 4, 17*4,  50*4, 1},	//	Rank 4
			{23, 30, 4, 17*5,  50*4, 1},	//	Rank 5
			{28, 30, 4, 100*1, 50*5, 1},	//	Rank 6
			{28, 30, 4, 100*2, 50*5, 1},	//	Rank 7
			{24, 31, 4, 17*2,  50*3, 1},	//	Rank 8
			{24, 31, 4, 17*3,  50*3, 1},	//	Rank 9
			{24, 31, 4, 17*3,  50*3, 1},	//	Rank 10
			{32, 31, 4, 100*2, 50*4, 1},	//	Rank 11
			{32, 31, 4, 100*3, 50*4, 1},	//	Rank 12
			{26, 31, 4, 2*10,  50*5, 1},	//	Rank 13
			{26, 31, 4, 2*20,  50*5, 1},	//	Rank 14
			{26, 31, 4, 2*30,  50*5, 1},	//	Rank 15

			{22, 31, 4, 17*4,	50*4, 1}	//  Default Weapons
		},
		{
			{22, 29, 4, 17*3,	30*2, 1},
			{22, 29, 4, 17*4,	30*2, 1},
			{22, 29, 4, 17*5,	30*2, 1},
			{22, 29, 4, 17*6,	30*3, 1},
			{23, 29, 4, 17*2,	30*3, 1},
			{23, 29, 4, 17*3,	30*3, 1},
			{23, 29, 4, 17*4,	30*3, 1},
			{24, 29, 4, 17*2,	30*4, 1},
			{24, 29, 4, 17*3,	30*4, 1},
			{24, 29, 4, 17*4,	30*4, 1},
			{24, 29, 4, 17*5,	30*5, 1},
			{26, 29, 4, 2*10,	30*5, 1},
			{26, 29, 4, 2*15,	30*6, 1},
			{26, 29, 4, 2*20,	30*6, 1},
			{26, 29, 4, 2*25,	30*6, 1},

			{22, 29, 4, 17*4,	30*5, 1}
		},
		{
			{22, 34, 4, 17*3,  20,   1},
			{22, 34, 4, 17*4,  20,   1},
			{22, 34, 4, 17*5,  20,   1},
			{23, 34, 4, 17*4,  30,   1},
			{23, 34, 4, 17*5,  30,   1},
			{28, 34, 4, 100*1, 50,   1},
			{28, 34, 4, 100*2, 50,   1},
			{24, 34, 4, 17*2,  60,   1},
			{24, 34, 4, 17*3,  60,   1},
			{24, 34, 4, 17*3,  80,   1},
			{32, 34, 4, 100*2, 80,   1},
			{32, 34, 4, 100*3, 90,   1},
			{26, 34, 4, 2*10,  100,  1},
			{26, 34, 4, 2*20,  100,  1},
			{26, 34, 4, 2*30,  100,  1},

			{22, 34, 4, 17*4,	50,	  1}
		},
		{
			{22, 25, 4, 17*3,  20,   1},
			{22, 25, 4, 17*4,  30,   1},
			{22, 25, 4, 17*5,  40,   1},
			{23, 25, 4, 17*4,  50,   1},
			{23, 25, 4, 17*5,  60,   1},
			{28, 25, 4, 100*1, 70,   1},
			{28, 25, 4, 100*2, 80,   1},
			{24, 27, 4, 17*2,  7*3,  1},
			{24, 27, 4, 17*3,  7*4,  1},
			{24, 27, 4, 17*3,  7*5,  1},
			{32, 27, 4, 100*2, 7*6,  1},
			{32, 27, 4, 100*3, 7*7,  1},
			{26, 27, 4, 2*10,  7*8,  1},
			{26, 27, 4, 2*20,  7*9,  1},
			{26, 27, 4, 2*30,  7*10, 1},

			{22, 25, 4, 17*4,	30,  1}
		}
	};

	new pKillCount[MAX_PLAYERS][MAX_WEAPON];

//======================Skin Arrays

	new
		RavenSkins[5]=
		{
			124,
			126,
			127,
			125
		},
		ValorSkins[7]=
		{
			30,
			247,
			100,
			248
		},
		FFASkins[20]=
		{
		    122,
		    117,
		    118,
		    120,
		    247,
		    248,
		    254,
		    111,
		    112,
		    113,
		    124,
		    125,
		    126,
		    127,
		    285,
		    287,
		    165,
		    166,
		    179
		};

//======================Kit Variables

	new
		TotalSupplies[MAX_PLAYERS],
		TotalHeal[MAX_PLAYERS],
		TotalMines[MAX_PLAYERS],
		TotalRepair[MAX_PLAYERS];

//======================Supply Boxes

	new
		SupplyBox[MAX_AMMO_CRATE],
		Float:SupplyPos[MAX_AMMO_CRATE][3],
		SupplyArea[MAX_AMMO_CRATE],
		bool:CrateIdUsed[MAX_AMMO_CRATE],
		SupplyCount[MAX_AMMO_CRATE],
		tick_AllowedAmmo[MAX_PLAYERS];

	AddSupplyCrate(Float:x, Float:y, Float:z, Float:r=0.0, playerid=INVALID_PLAYER_ID)
	{
		new ID, modID=964;
		while(CrateIdUsed[ID])ID++;
		if(playerid!=INVALID_PLAYER_ID)
		{
		    ID=playerid+20;
		    if(bPlayerGameSettings[playerid]&SupplyActive)DestroySupplyCrate(ID);
		    bitTrue(bPlayerGameSettings[playerid], SupplyActive);
			modID=3052;
			SupplyCount[ID]=5;
		}
		SupplyBox[ID]=CreateDynamicObject(modID, x, y, z, 0, 0, r, DEATHMATCH_WORLD);
		SupplyArea[ID]=CreateDynamicSphere(x, y, z, 2.0, DEATHMATCH_WORLD);
		SupplyPos[ID][0]=x,
		SupplyPos[ID][1]=y,
		SupplyPos[ID][2]=z;
		CrateIdUsed[ID]=true;
		return ID;
	}
	DestroySupplyCrate(id, playerid=-1)
	{
		SupplyPos[id][0]=0,
		SupplyPos[id][1]=0,
		SupplyPos[id][2]=0;
		SupplyCount[id]=0;
		DestroyDynamicObject(SupplyBox[id]);
		CrateIdUsed[id]=false;
		if(playerid!=-1)bitFalse(bPlayerGameSettings[playerid], SupplyActive);
	}
	ReSupplyPlayer(playerid)
	{
		SetPlayerHP(playerid, GlobalMaxHP);
		bitTrue(bPlayerDeathmatchSettings[playerid], GearUse);
		PlayerShotBy[playerid]=FreeID;
		GivePlayerKitWeapons(playerid, 1);
	}

//======================Supply Boxes (Arcade Mode)

	new ArcadeWepData[18][3]=
	{
	//  id   wep   ammo
		{22, 100, 50},
		{23, 250, 120},
		{24, 900, 300},

		{25, 800, 350},
		{26, 850, 400},
		{27, 1000, 500},

		{30, 800, 350},
		{31, 1000, 500},

		{28, 700, 300},
		{29, 850, 400},

		{33, 500, 150},
		{34, 600, 250},

		{18, 500, 500},
		{16, 500, 500},
		{39, 1000, 1000},

		{35, 5000, 1000},
		{37, 5000, 1000},
		{38, 10000, 4000}
	},
	SelectedItem[MAX_PLAYERS];

//======================Mines

	new
		Mine				[MAX_MINES],
		Float:MinePos		[MAX_MINES][3],
		MineOwner			[MAX_MINES],
		bool:MineExploded	[MAX_MINES],
		MineProx			[MAX_MINES],
		MineLoc				[MAX_MINES],
		MineID_Used         [MAX_MINES];

	stock CreateMine(playerid, Float:x, Float:y, Float:z)
	{
		new ID;
		while(MineID_Used[ID])ID++;
		Mine[ID] = CreateDynamicObject(1252, x, y, z, 90, 0, 0);
		MinePos[ID][0] = x;
		MinePos[ID][1] = y;
		MinePos[ID][2] = z;
		MineOwner[ID] = playerid;
		MineExploded[ID] = false;
		MineProx[ID]=CreateDynamicSphere(x, y, z, MINE_TRIG_RAD);
		MineLoc[ID]=CreateDynamicSphere(x, y, z, MINE_TRIG_RAD*3);
		MineID_Used[ID]=true;
	}
	stock ExplodeMine(mineID)
	{
		CreateExplosion(MinePos[mineID][0], MinePos[mineID][1], MinePos[mineID][2], 12, 3.0);
		DestroyDynamicObject(Mine[mineID]);
		MineExploded[mineID] = true;
		MineOwner[mineID] = FreeID;
		DestroyDynamicArea(MineProx[mineID]);
		DestroyDynamicArea(MineLoc[mineID]);
		MineID_Used[mineID]=false;
	}

//======================Icon Update Function

	UpdatePlayerIcons(playerid)
	{
		PlayerLoop(i)
	    {
	        if(!(bPlayerGameSettings[i]&Spawned))
	        {
				SetPlayerMarkerForPlayer	(playerid, i, 0xAFAFAF00);
				ShowPlayerNameTagForPlayer	(playerid, i, false);
				SetPlayerMarkerForPlayer	(i, playerid, 0xAFAFAF00);
				ShowPlayerNameTagForPlayer	(i, playerid, false);
	        }
			else if(pTeam(i)==pTeam(playerid))
			{
				SetPlayerMarkerForPlayer(playerid, i, FRIENDLY_PLAYER_VISIBLE);
				SetPlayerMarkerForPlayer(i, playerid, FRIENDLY_PLAYER_VISIBLE);
				ShowPlayerNameTagForPlayer(playerid, i, true);
				ShowPlayerNameTagForPlayer(i, playerid, true);
			}
			else if(pTeam(i)==poTeam(playerid))
			{
				SetPlayerMarkerForPlayer(playerid, i, ENEMY_PLAYER_INVISIBLE);
				SetPlayerMarkerForPlayer(i, playerid, ENEMY_PLAYER_INVISIBLE);
				ShowPlayerNameTagForPlayer(playerid, i, false);
				ShowPlayerNameTagForPlayer(i, playerid, false);
			}
			else
			{
				SetPlayerMarkerForPlayer(playerid, i, WHITE);
				SetPlayerMarkerForPlayer(i, playerid, WHITE);
				ShowPlayerNameTagForPlayer(playerid, i, false);
				ShowPlayerNameTagForPlayer(i, playerid, false);
			}
		}
	}
	

//======================Team Functions

	stock GetPlayersInTeam(teamid)
	{
		new PinT;
		PlayerLoop(i)if(pTeam(i)==teamid)PinT++;
		return PinT;
	}
	TeamMsg(teamid, colour, msg[])
	{
		PlayerLoop(i)if(pDM_Data[i][Team]==teamid)msg(i, colour, msg);
		return 1;
	}
	GameMsg(colour, msg[])
	{
	    PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)msg(i, colour, msg);
	    return 1;
	}

	SetPlayerToTeam(pid, team)
	{
		if(team==0||team==1)
		{
			if(bDeathmatchSettings&FriendlyFire)SetPlayerTeam(pid, NO_TEAM);
			else SetPlayerTeam(pid, team);
		}
		else if(team>=10&&team<=10+MAX_PLAYERS)
		{
		    SetPlayerTeam(pid, team);
		}
		pDM_Data[pid][Team] = team;
		SetPlayerTeamSkin(pid);
	}
	SetPlayerTeamSkin(pid)
	{
		if(pDM_Data[pid][Team] == 0)
		{
			SetPlayerSkin(pid, RavenSkins[pKit(pid)]);
			if(bDeathmatchSettings&GearItemUsage&&pGear(pid)==g_Disguise)SetPlayerSkin(pid, ValorSkins[pKit(pid)]);
		}
		else if(pDM_Data[pid][Team] == 1)
		{
			SetPlayerSkin(pid, ValorSkins[pKit(pid)]);
			if(bDeathmatchSettings&GearItemUsage&&pGear(pid)==g_Disguise)SetPlayerSkin(pid, RavenSkins[pKit(pid)]);
		}
		else if(pDM_Data[pid][Team]>=10||pDM_Data[pid][Team]<=10+MAX_PLAYERS)SetPlayerSkin(pid, FFASkins[random(sizeof(FFASkins))]);
	}


//======================Enf Match Stats Functions

	MostKills()
	{
		new w_P, w_A;
		PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)if(DM_Kills(i)>w_A)w_A=DM_Kills(i),w_P=i;
		return w_P;
	}
	MostDeaths()
	{
		new w_P, w_A;
		PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)if(DM_Deaths(i)>w_A)w_A=DM_Deaths(i),w_P=i;
		return w_P;
	}
	MostXP()
	{
		new w_P, w_A;
		PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)if(DM_Exp(i)>w_A)w_A=DM_Exp(i),w_P=i;
		return w_P;
	}
	enum rankingEnum
	{
	    player_Score,
	    player_ID
	}
	LeaderBoard(array[][rankingEnum], left, right)
	{
	    new index;
		PlayerLoop(i)
		{
		    if(bPlayerGameSettings[i]&InDM&&IsPlayerConnected(i))
		    {
				array[index][player_Score]=DM_Exp(i);
				array[index][player_ID]=i;
				++index;
			}
		}
	    new
	        tempLeft = left,
	        tempRight = right,
	        pivot = array[(left + right) / 2][player_Score],
	        tempVar;
	    while(tempLeft <= tempRight)
	    {
	        while(array[tempLeft][player_Score] > pivot) tempLeft++;
	        while(array[tempRight][player_Score] < pivot) tempRight--;

	        if(tempLeft <= tempRight)
	        {
	            tempVar = array[tempLeft][player_Score], array[tempLeft][player_Score] = array[tempRight][player_Score], array[tempRight][player_Score] = tempVar;
	            tempVar = array[tempLeft][player_ID], array[tempLeft][player_ID] = array[tempRight][player_ID], array[tempRight][player_ID] = tempVar;
	            tempLeft++, tempRight--;
	        }
	    }
	    if(left < tempRight) LeaderBoard(array, left, tempRight);
	    if(tempLeft < right) LeaderBoard(array, tempLeft, right);
	}

//======================Player XP and Notification Functions

	new
		Text:XPtext[MAX_PLAYERS],
		oldamount[MAX_PLAYERS],
		oldmsg[MAX_PLAYERS][MAX_XPMSG_LEN],
		xpMsgLines[MAX_PLAYERS],
		XPtimer[MAX_PLAYERS];

	GiveXP(playerid, amount, msg[])
	{
		new
			szTextString[MAX_XPMSG_LEN],
			szExpString[MAX_XPINT_LEN],
			szFinalString[MAX_XPMSG_LEN];

		TextDrawHideForPlayer(playerid, XPtext[playerid]);
//	    msgF(playerid, YELLOW, "-   lines: %d", xpMsgLines[playerid]+1);
		xpMsgLines[playerid]++;
		if(bPlayerDeathmatchSettings[playerid]&ExpMsgShowing)
		{
			format(szTextString, MAX_XPMSG_LEN, "~b~%d ~y~%s~n~%s", amount, msg, oldmsg[playerid]);
			if(xpMsgLines[playerid]>MAX_XPMSG_LINE)
			{
			    new nlPos, len=strlen(szTextString);
			    for(nlPos=len;nlPos>=0;nlPos--)if(szTextString[nlPos]=='~')break;
			    for(new x=nlPos-2;x<len;x++)szTextString[x]=0;
				xpMsgLines[playerid]--;
			}
			format(szExpString, MAX_XPINT_LEN, "%dXP", oldamount[playerid]+amount);
			format(oldmsg[playerid], MAX_XPMSG_LEN, szTextString);
			KillTimer(XPtimer[playerid]);
		}
		else
		{
			format(szTextString, MAX_XPMSG_LEN, "~b~%d ~y~%s", amount, msg);
			format(szExpString, MAX_XPINT_LEN, "%dXP", amount);
			format(oldmsg[playerid], MAX_XPMSG_LEN, szTextString);
		}
		bitTrue(bPlayerDeathmatchSettings[playerid], ExpMsgShowing);
		oldamount[playerid]+=amount;
		format(szFinalString, MAX_XPMSG_LEN, "~b~%s~n~%s", szExpString, szTextString);


		TextDrawSetString(XPtext[playerid], szFinalString);
		TextDrawShowForPlayer(playerid, XPtext[playerid]);
		XPtimer[playerid]=SetTimerEx("ExpMsgDestroy", EXP_TEXT_HIDE, false, "d", playerid);

		pExp(playerid)+=amount;

		RankCheck(playerid);
		UpdatePlayerXPBar(playerid);
	}
	public ExpMsgDestroy(playerid)
	{
		TextDrawHideForPlayer(playerid, XPtext[playerid]);
		oldamount[playerid]=0;
		oldmsg[playerid][0]=EOS;
		xpMsgLines[playerid]=0;
		bitFalse(bPlayerDeathmatchSettings[playerid], ExpMsgShowing);
		if(pDM_Data[playerid][Combo]>0)pDM_Data[playerid][Combo]=0;
	}
	stock GiveTeamXP(teamid, amount, msg[]="")PlayerLoop(i)if(bPlayerGameSettings[i]&InDM&&pDM_Data[i][Team]==teamid)GiveXP(i,amount,msg);

//======================Update XP Text Draw Bar for player

	stock UpdatePlayerXPBar(playerid)
	{
		SetProgressBarValue(XPbar[playerid], pExp(playerid)-RequiredExp[pRank(playerid)]);
		SetProgressBarMaxValue(XPbar[playerid], RequiredExp[pRank(playerid)+1]-RequiredExp[pRank(playerid)]);
		UpdateProgressBar(XPbar[playerid], playerid);
	}

//======================General Deathmatch Data Variables

	new
		GEN_FileDataKeys[9][14]=
		{
			"GEN_CamPos",
			"GEN_Weather",
			"GEN_Time",
			"GEN_Author",
		    "GEN_spawn1",
		    "GEN_spawn2",
		    "GEN_Info_Bio",
			"GEN_Info_Size",
			"Gen_Info_Kit"
		};

//=======================Map related Variables

	new OutskirtsElevator, MAP23_ElevatorT, MAP23_ElevatorB, ElevatorPos;

//======================PlayersInLobby and PlayersInDM functions

	stock GetPlayersInLobby()
	{
		new iPlayers;
		PlayerLoop(i)if(bPlayerGameSettings[i]&InLobby)iPlayers++;
		return iPlayers;
	}
	stock GetPlayersInDM()
	{
		new iPlayers;
		PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)iPlayers++;
		return iPlayers;
	}

//======================Match Timer Stuff

	#define timers 100
	new
		Text:MatchTimeCounter,
		Tsec,
		Tmin,
		TimerActive;

	MatchTime(minutes, seconds)
	{
		Tmin = minutes;
		Tsec = seconds;
		TimerActive=true;
		return 1;
	}
	StopMatchTime()
	{
		TimerActive=false;
	 	TextDrawHideForAll(MatchTimeCounter);
	}
	PauseMatchTime()TimerActive=false;
	ContinueMatchTime()TimerActive=true;
	TimerSet()
	{
		new string[6], M[3], S[3];
		if(Tsec >= 1) Tsec--;
		if(Tsec < 10) format(S, 3, "0%d", Tsec);
		else format(S, 3, "%d", Tsec);
		if(Tmin < 10) format(M, 3, "0%d", Tmin);
		else format(M, 3, "%d", Tmin);
		if(Tsec <= 0 && Tmin != 0) Tsec = 59, Tmin--;
		else if(Tmin == 0 && Tsec == 0)
		{
			TimerActive=false;
			EndMatchTime();
		}
		format(string, 6, "%s:%s",M, S);
		TextDrawSetString(MatchTimeCounter, string);
		return 1;
	}
	EndMatchTime()
	{
	 	TextDrawHideForAll(MatchTimeCounter);
		Tmin = 1000;
		Tsec = 1000;
		EndRound();
	 	return 1;
	}

//======================Libraries of Seperate Scripts

#include "../scripts/Deathmatch/script_MAP02.pwn"

#include "../scripts/Deathmatch/KitEquip.pwn"


#include "../scripts/Deathmatch/gm0_TDM.pwn"
#include "../scripts/Deathmatch/gm1_AD.pwn"
#include "../scripts/Deathmatch/gm2_CTF.pwn"
#include "../scripts/Deathmatch/gm3_CQST.pwn"



//======================Player Awards
	#define fist		0
	#define knife_3		1
	#define knife_6		2

	#define nine_6		3
	#define nine_9		4
	#define nine_m		5

	#define ninesd_6	6
	#define ninesd_9	7
	#define ninesd_m	8

	#define mac10_6		9
	#define mac10_9		10
	#define mac10_m		11

	#define deagle_6	12
	#define deagle_9	13
	#define deagle_m	14

	#define tec9_6		15
	#define tec9_9		16
	#define tec9_m		17

	#define sawnoff_6	18
	#define sawnoff_9	19
	#define sawnoff_m	20

	#define mp5_6		21
	#define mp5_9		22
	#define mp5_m		23

	#define shotgun_6	24
	#define shotgun_9	25
	#define shotgun_m	26

	#define ak47_6		27
	#define ak47_9		28
	#define ak47_m		29

	#define spas_6		30
	#define spas_9		31
	#define spas_m		32

	#define m4_6		33
	#define m4_9		34
	#define m4_m		35

	#define sniper_3	36
	#define sniper_6	37
	#define sniper_10	38
	#define sniper_m	39
	#define sniper_l	40

	#define sachel		41
	#define grenade		42
	#define molotov		43
	#define mine		44

	#define rocket_2	45
	#define rocket_4	46

	#define flamer_10	47
	#define flamer_20	48
	#define minigun_10	49
	#define minigun_20	50

enum AwardDataEnum
{
	wepid,
	awdAbv[11],
	awdName[40],
	awdReq,
	awdRew
}
new
	AwardData[][AwardDataEnum]=
	{
	    {0, "fist", "Beatdown", 1, 10},
		{4, "knife_3","Shankman", 3, 30},
		{4,	"knife_6","Stealth Killer", 6, 60},

		{22, "nine_6","cap-in-yo-ass", 6, 20},
		{22, "nine_9","Gunslinger", 9, 30},
		{22, "nine_m","9mm Master", 20, 50},

		{23, "ninesd_6","Dead Silenced", 6, 20},
		{23, "ninesd_9","James Bond", 9, 30},
		{23, "ninesd_m","9mmSD Master", 20, 50},

		{28, "mac10_6","Auto-Kill", 6, 20},
		{28, "mac10_9","Handheld", 9, 30},
		{28, "mac10_m","MAC10 Master", 20, 50},

		{24, "deagle_6","Bullseye", 6, 20},
		{24, "deagle_9","Point-Blank", 9, 30},
		{24, "deagle_m","D-Eagle Master", 20, 50},

		{32, "tec9_6","Single Handed", 6, 20},
		{32, "tec9_9","Semi-Auto Killer", 9, 30},
		{32, "tec9_m","Tec9 Master", 20, 50},

		{26, "sawnoff_6","Buckshot", 6, 20},
		{26, "sawnoff_9","2-Pack", 9, 30},
		{26, "sawnoff_m","Sawnoff Master", 20, 50},

		{29, "mp5_6","Round Burst", 6, 20},
		{29, "mp5_9","Swat Raid", 9, 30},
		{29, "mp5_m","MP5 Master", 20, 50},

		{25, "shotgun_6","RedNeck", 6, 20},
		{25, "shotgun_9","Pump Action", 9, 30},
		{25, "shotgun_m","Shotgun Master", 20, 50},

		{30, "ak47_6","Cheapo Weapons", 6, 20},
		{30, "ak47_9","Russian Gold", 9, 30},
		{30, "ak47_m","AK47 Master", 20, 50},

		{27, "spas_6","Close Quarters", 6, 20},
		{27, "spas_9","12 Guage Killer", 9, 30},
		{27, "spas_m","Spas12 Master", 20, 50},

		{31, "m4_6","Devil Dog", 6, 20},
		{31, "m4_9","Trigger Happy", 9, 30},
		{31, "m4_m","M4 Master", 20, 50},

		{34, "sniper_3","Marksman", 3, 20},
		{34, "sniper_6","SharpShooter", 6, 30},
		{34, "sniper_10","Invisible", 10, 50},
		{34, "sniper_m","Sniper Master", 20, 100},
		{34, "sniper_l","Longrange", -1, 80},

		{39, "sachel","Remote Explosives", 3, 40},
		{16, "gremade","Grenadier", 3, 20},
		{18, "molotov","Cocktail", 3, 30},
		{50, "mine","Claymore", 3, 30},

		{35, "rocket_2","Rocket Propelled Kill", 2, 20},
		{35, "rocket_4","RPG Master", 4, 30},

		{37, "flamer_10","Playing With Fire", 10, 20},
		{37, "flamer_20","Flamer Master", 20, 30},

		{38, "minigun_10","Wraith", 10, 20},
		{38, "minigun_20","MiniMaster", 20, 30}
	};
	GiveAward(playerid, award)
	{
		file_Open(GetFile(playerid));
		file_IncVal(AwardData[award][awdAbv], 1);
		file_Close();
	}
	GetAwardList(playerid)
	{
		static str[600], oldstr[600];
		file_Open(GetFile(playerid));
		format(oldstr, 300, "%d\t\t%s", file_GetVal(AwardData[0][awdAbv]), AwardData[0][awdName]);
		for(new x=1;x<sizeof(AwardData);x++)
		{
		    format(str, 600, "%s\n%d\t\t%s", oldstr, file_GetVal(AwardData[x][awdAbv]), AwardData[x][awdName]);
		    oldstr=str;
		}
		file_Close();
		return str;
	}

/*
new WeaponTypes[4][10]=
{
	{
		//Melee
		2,	// club
		3,	// nitestick
		4,	// knife
		5,	//  bat
		6,	// shovel
		7,	//  cue
		8,	//  katana
		9,	//  chainsaw
		14,	//  flowers
		15	//  cane
	},
	{
		//SideArms
		22,	// 9mm
		23,	//  9mmSD
		28,	//  mac10
		24,	//  deagle
		32,	//  tec9
		26	//  sawnoff
	},
	{
		//Primary
		29,	//  mp5
		25,	//  shotgun
		30,	//  ak47
		27,	//  spas12
		31,	//  m4
		34	//  sniper
	},
	{
		//Equipment
		18,	//  molotov
		16,	//  grenage
		39,	//  c4
		35,	//  RPG
		36,	//  Heatseek
		37,	//  Flamer
		38	//  minigun
	}
};*/
GetWeaponType(id)
{
	switch(id)
	{
		case 2..9,14,15:return 0;               // Melee
		case 22,23,24,26,28,32:return 1;        // Secondary
		case 25,27,29,30,31,34:return 2;        // Primary
		case 16,18,35,36,37,38,39:return 3;     // Equipment
		default:return -1;
	}
	return -1;
}
HasWeaponType(playerid, type)
{
	new W, A;
	for(new w;w<13;w++)
	{
		GetPlayerWeaponData(playerid, w, W, A);
	    if(GetWeaponType(W) == type && A>0)return W;
	}
	return -1;
}
new
	WepObj[MAX_DM_WEP],
	WepSpr[MAX_DM_WEP],
	WepId[MAX_DM_WEP],
	WepAmo[MAX_DM_WEP],
	Float:WepPos[MAX_DM_WEP][6],
	bool:IdUsed[MAX_DM_WEP];
AddWeaponPickup(Float:x, Float:y, Float:z, weaponid, ammo, Float:rx=90.0, Float:ry=0.0, Float:rz=0.0, Float:zminus=0.8)
{
	new ID;
	while(IdUsed[ID])ID++;
	WepObj[ID]=CreateDynamicObject(WepData[weaponid][WepModel], x, y, z-zminus, rx, ry, rz);
	WepSpr[ID]=CreateDynamicSphere(x, y, z, 1.0);
	WepId[ID]=weaponid,WepAmo[ID]=ammo;
	WepPos[ID][0]=x,WepPos[ID][1]=y,WepPos[ID][2]=z,WepPos[ID][3]=rx,WepPos[ID][4]=ry,WepPos[ID][5]=rz;
	IdUsed[ID]=true;
	return ID;
}
PlayerPickUpWeapon(playerid, id)
{
	static pWep, pAmmo, Float:pos[6];
	for(new slot;slot<12;slot++)
	{
		GetPlayerWeaponData(playerid, slot, pWep, pAmmo);
		if(GetWeaponType(pWep)==GetWeaponType(WepId[id]))
		{
			SetPlayerAmmo(playerid, pWep, 0);
			GivePlayerWeapon(playerid, WepId[id], WepAmo[id]);
			pos[0]=WepPos[id][0], pos[1]=WepPos[id][1], pos[2]=WepPos[id][2], pos[3]=WepPos[id][3], pos[4]=WepPos[id][4], pos[5]=WepPos[id][5];
			DestroyWeaponPickup(id);
			AddWeaponPickup(pos[0], pos[1], pos[2], pWep, pAmmo, pos[3], pos[4], pos[5]);
			break;
		}
	}
}
DestroyWeaponPickup(id)
{
	DestroyDynamicObject	(WepObj[id]);
	DestroyDynamicArea		(WepSpr[id]);
	WepId[id]				=FreeID,
	WepAmo[id]				=FreeID;
	WepPos[id][0]=0.0,WepPos[id][1]=0.0,WepPos[id][2]=0.0,WepPos[id][3]=0.0,WepPos[id][4]=0.0,WepPos[id][5]=0.0;
	IdUsed[id]=false;
}



IsPlayerInGame(playerid)
{
	if ( !(bPlayerGameSettings[playerid]&InLobby) && !(bPlayerGameSettings[playerid]&ReadyForDM) )return 1;
	return 0;
}

script_Deathmatch_GlobalUpdate()
{
	if(bServerGlobalSettings&DMstarted)
	{
		SpawnCounter--;
		new str[15];
		format(str, 15, "Spawning in %d", SpawnCounter);
		TextDrawSetString(SpawnCount, str);
		if(SpawnCounter<=0)
		{
			PlayerLoop(i)if((bPlayerGameSettings[i]&ReadyForDM)&&(bServerGlobalSettings&DMstarted))DMspawn(i);
			SpawnCounter=MAX_SPAWN_COUNT;
		}
	}
	for(new cp;cp<MAX_CP;cp++)if(CPtimer[cp])CP_CaptureUpdate(FirstToCapture[cp], cp);
	if(bServerGlobalSettings&LobbyCountingDown)UpdateQueueCountDown();
	if(TimerActive)TimerSet();
	if(PointCT)AD_CaptureUpdate(capturer);
}

script_Deathmatch_PlayerUpdate(playerid)
{
	if((bPlayerDeathmatchSettings[playerid]&Spawned)&&!(bPlayerDeathmatchSettings[playerid]&BleedingOut)&&!(bDeathmatchSettings&Hardcore)&&(PlayerHP[playerid]<GlobalMaxHP))
	{
		if(PlayerHP[playerid]>=(GlobalMaxHP/2))SetPlayerHP(playerid, (PlayerHP[playerid]+(GlobalMaxHP/(MAX_HEALTH/2))));
		if(PlayerHP[playerid]<=(GlobalMaxHP/2))SetPlayerHP(playerid, (PlayerHP[playerid]+(GlobalMaxHP/(MAX_HEALTH/3))));
		if(PlayerHP[playerid]<=(GlobalMaxHP/5))GameTextForPlayer(playerid, "~n~~n~~n~~r~(YOU ARE HURT)~n~(GET TO COVER!)", 1000, 5);
	}
	UpdateHealthBar(playerid);
	if(bPlayerDeathmatchSettings[playerid]&BleedingOut)
	{
		if(GetPlayerAnimationIndex(playerid)!=1207/*||GetPlayerAnimationIndex(playerid)!=GETUP ANIM*/)ApplyAnimation(playerid, "ped", "KO_shot_stom", 1, 0, 0, 0, 1, 0, 1);
		Blood[playerid]--;
		SetProgressBarValue(BleedoutBar[playerid], Blood[playerid]);
		UpdateProgressBar(BleedoutBar[playerid], playerid);
		if(Blood[playerid]<=0)
		{
		    if(BleedAttacker[playerid]==INVALID_PLAYER_ID)OnDeath(playerid);
		    else script_Deathmatch_OnPlayerKill(playerid, BleedAttacker[playerid], BleedReason[playerid]);
			ExitBleedOut(playerid);
		}
	}
	if(CPFlash[CapturingCP[playerid]]!=-1)
	{
	    if(CPFlash[CapturingCP[playerid]])ShowProgressBarForPlayer(playerid, CPbar[CapturingCP[playerid]]);
	    if(!CPFlash[CapturingCP[playerid]])HideProgressBarForPlayer(playerid, CPbar[CapturingCP[playerid]]);
		CPFlash[CapturingCP[playerid]]=!CPFlash[CapturingCP[playerid]];
	}
	SetPlayerWeather(playerid, DMweather);
	SetPlayerTime(playerid, DMtime_H, DMtime_M);
}
script_Deathmatch_PlayerShoot(playerid)
{
	bitTrue(bPlayerGameSettings[playerid], Shooting);
	for(new i=0;i<MAX_MINES;i++)if(IsPlayerAimingAt(playerid, MinePos[i][0], MinePos[i][1], MinePos[i][2]+0.1, 0.6) && MineID_Used[i])ExplodeMine(i);
}
script_Deathmatch_hitPlayer(playerid, targetid, head, weapon)
{
	if(bPlayerGameSettings[targetid]&BleedingOut)
	{
	    PlayerShotBy[targetid]=playerid;
		Blood[targetid]-=10.0;
		return 1;
	}
	if( !(bDeathmatchSettings&FriendlyFire) && (pTeam(playerid)==pTeam(targetid)) ) return 1;

	new
		Float:HpLoss = frandom(WepData[weapon][MaxDam], WepData[weapon][MinDam]),
		Float:p_pos[3],
		Float:t_pos[3];
	GetPlayerPos(playerid, p_pos[0], p_pos[1], p_pos[2]);
	GetPlayerPos(targetid, t_pos[0], t_pos[1], t_pos[2]);

	TextDrawShowForPlayer(playerid, HitMark);
	SetTimerEx("HideHitMark", 500, false, "d", playerid);
	PlayerShotBy[targetid]=playerid;

	if( IsPlayerInRangeOfPoint(playerid, 1.5, t_pos[0], t_pos[1], t_pos[2]) && IsPlayerFacingPlayer(playerid, targetid, 60) && IsPlayerBehindPlayer(playerid, targetid, 10) )HpLoss+=frandom( (GlobalMaxHP*0.5), GlobalMaxHP);
    if(head)
	{
		if(bDeathmatchSettings&InstaHS)HpLoss=GlobalMaxHP;
		else HpLoss+=(GlobalMaxHP*0.9);
	}
	if(bDeathmatchSettings&GearItemUsage)
	{
    	if(pGear(playerid)==g_ProxDet)GameTextForPlayer(targetid, "~r~Warning ~n~-~n~ Shots Fired", 1000, 5);
	    if(pGear(playerid)==g_G12&&(weapon==Spas12||weapon==Shotgun) && (GetPlayerDist3D(playerid, targetid) <= 10) ) HpLoss+=(GlobalMaxHP*0.2);
		if(pGear(playerid)==g_FMJ)HpLoss+=(GlobalMaxHP*0.1);
	}
    if((bPlayerDeathmatchSettings[targetid]&PlayingDead) || (bPlayerDeathmatchSettings[targetid]&BleedingOut))HpLoss=GlobalMaxHP;


	SetPlayerHP(targetid, (PlayerHP[targetid]-HpLoss), playerid, weapon, head);

	if(bServerGlobalSettings&DebugMode)
	{
		msgF(playerid, ORANGE, "Did "#C_WHITE"%f"#C_RED" Damage {FFFF00}(AFTER HP MODIFIERS)", HpLoss);
		msgF(targetid, RED, "Took "#C_WHITE"%f"#C_RED" Damage {FFFF00}(AFTER HP MODIFIERS)", HpLoss);
	}
	return 1;
}
public HideHitMark(playerid)TextDrawHideForPlayer(playerid, HitMark);

SetPlayerHP(targetid, Float:amount, playerid=INVALID_PLAYER_ID, weapon=0, head=0, bleed=1)
{
	if(!(bPlayerGameSettings[targetid]&Spawned))return 0;
	if(amount <= 0.0)
	{
		if(playerid==INVALID_PLAYER_ID)script_Deathmatch_OnPlayerDie(targetid);
		else
		{
			if(bDeathmatchSettings&Revive && !head && bleed)EnterBleedout(targetid, playerid);
			else script_Deathmatch_OnPlayerKill(targetid, playerid, weapon, head);
		}
	}
	PlayerHP[targetid]=amount;
	UpdateHealthBar(targetid);
	return 1;
}

CMD:bleedout(playerid, params[])
{
	SetPlayerHP(playerid, 0.0);
	return 1;
}

EnterBleedout(playerid, attacker=INVALID_PLAYER_ID, weapon=0)
{
	static
		Float:cx,
		Float:cy,
		Float:cz,
		Float:px,
		Float:py,
		Float:pz;
	GetPlayerPos(playerid, px, py, pz);
	GetPlayerCameraPos(playerid, cx, cy, cz);

	TogglePlayerControllable(playerid, false);
	ApplyAnimation(playerid, "ped", "KO_shot_stom", 1, 0, 0, 0, 1, 0, 1);
	bitTrue(bPlayerDeathmatchSettings[playerid], BleedingOut);
	Blood[playerid]=30;
	BleedAttacker[playerid]=attacker;
	BleedReason[playerid]=weapon;
	DownedPlayers++;
	PlayerProximity[playerid]=CreateDynamicSphere(px, py, pz, 2.0, DEATHMATCH_WORLD);

	ShowProgressBarForPlayer(playerid, BleedoutBar[playerid]);
	SetProgressBarMaxValue(BleedoutBar[playerid], 30);
	ShowMsgBox(playerid, "Press ~r~"#TEXT_ACTION_KEY" ~w~to Bleed-Out");

	SetPlayerCameraLookAt(playerid, px, py, pz);
	SetPlayerCameraPos(playerid, cx, cy, cz);
}
ExitBleedOut(playerid)
{
	HideProgressBarForPlayer(playerid, BleedoutBar[playerid]);
	HideMsgBox(playerid);

	bitFalse(bPlayerDeathmatchSettings[playerid], BleedingOut);
	DownedPlayers--;
	return 1;
}

UpdateHealthBar(playerid)
{
	new str[6];
	format(str, 6, "%dHP", floatround(PlayerHP[playerid]*(100/GlobalMaxHP)) );
	TextDrawSetString(HealthCount[playerid], str);
}

script_Deathmatch_OnPlayerDie(playerid)
{
	for(new i;i<MAX_MINES;i++)
	{
		if(MineOwner[i]!=-1)
		{
			if(IsPlayerInRangeOfPoint(playerid, MINE_TRIG_RAD, MinePos[i][0], MinePos[i][1], MinePos[i][2]+0.9))
			{
				if(MineExploded[i])
				{
					if(pTeam(playerid)!=pTeam(MineOwner[i]))
					{
						script_Deathmatch_OnPlayerKill(playerid, MineOwner[i], 50);
						break;
					}
				}
			}
		}
	}
	if(PlayerShotBy[playerid]!=FreeID)GiveXP(PlayerShotBy[playerid], 3, "assisted suicide");
	GiveXP(playerid, -1, "suicide!");

	OnDeath(playerid);
}
script_Deathmatch_OnPlayerKill(playerid, killerid, reason, head=0)
{
	DeathmatchDataUpdate(playerid, killerid);
	DropWep(playerid);

	if(GetTickCount()-tick_LastKill[killerid]<=500)return 0;
	static
		Float:DPX, Float:DPY, Float:DPZ,
		Float:KPX, Float:KPY, Float:KPZ;
	GetPlayerPos(playerid, DPX, DPY, DPZ);
	GetPlayerPos(killerid, KPX, KPY, KPZ);

	SetPlayerCameraPos(playerid, DPX, DPY, DPZ+0.2);
	SetPlayerCameraLookAt(playerid, KPX, KPY, KPZ);

	if(pTeam(killerid) != pTeam(playerid))
	{
	    TeamScore[Score][pTeam(killerid)]++;
		if(DMmode==DM_MODE_CQS)TeamScore[Ticket][pTeam(playerid)]--;
		if(DMmode==DM_MODE_AD)
		{
			if(pTeam(playerid)!=DefendingTeam)
			{
				TeamScore[Ticket][!DefendingTeam]--;
			}
		}

		ShowDeathMSG(playerid, killerid, reason);
		ScoreUpdate(playerid, killerid, reason, head);
		AwardUpdate(killerid, 0);

		tick_LastKill[killerid]=GetTickCount();
		tick_LastDeath[playerid]=GetTickCount();
		LastKilled[killerid]=playerid;
	}
	else
	{
		pInfo[killerid][pI_TeamKills]++;
		GiveXP(killerid, -10, "Teamkill");
		SetPlayerHP(killerid, 0.0);
		SetPlayerScore(killerid, GetPlayerScore(killerid)-1);
	}
	if(bDeathmatchSettings&GearItemUsage&&pGear(playerid)==g_Surprise)CreateExplosion(DPX, DPY, DPZ, 12, 5.0);
	SendDeathMessage(killerid, playerid, reason);
	UpdatePlayerIcons(killerid);
	
	OnDeath(playerid);
	return 1;
}
OnDeath(playerid)
{
	msg(playerid, YELLOW, "I haven't added the death animation yet! D:");
	bitFalse(bPlayerGameSettings[playerid], Spawned);
	tick_AllowedAmmo[playerid]=0;
	PlayerShotBy[playerid]=FreeID;
	pStreak(playerid)=0;

	SetPlayerHP(playerid, GlobalMaxHP);
	TeamScoreUpdate();
	UpdatePlayerIcons(playerid);
	SetTimerEx("JoinLobby", 3000, false, "d", playerid);
}
CMD:calldeath(playerid, params[])
{
	SetPlayerHP(playerid, 0.0);
	return 1;
}
/*
	if((bDeathmatchSettings&Revive)&&(bPlayerDeathmatchSettings[playerid]&BleedingOut))
	{
		bitFalse(bPlayerDeathmatchSettings[playerid], BleedingOut);
		HideProgressBarForPlayer(playerid, BleedoutBar[playerid]);
	}
*/
ShowDeathMSG(playerid, killerid, reason)
{
	new
		DeathMSG[250],
		kcMsg[53];


	if(pStreak(playerid)>3)format(kcMsg, 53, "~r~ended Streak of %d", pStreak(playerid));
	else kcMsg=" ";

	format(DeathMSG, 250, "Killed By: ~r~%s~n~~w~Weapon: ~b~%s~n~~w~Health: ~g~%d~n~~n~~w~Rank: ~b~%d~n~~w~Exp: ~b~%d~n~~w~Kills: ~b~%d~n~~w~Deaths: ~b~%d~n~~n~%s",
	GetName(killerid), WepData[reason][WepName], floatround(PlayerHP[killerid]*(100/GlobalMaxHP)), pRank(killerid), DM_Exp(killerid), DM_Kills(killerid), DM_Deaths(killerid), kcMsg);
	HideHUD(playerid);
	ShowMsgBox(playerid, DeathMSG);
}
ScoreUpdate(playerid, killerid, reason, head)
{
	GivePlayerMoney(killerid, 250);
	SetPlayerScore(killerid,GetPlayerScore(killerid)+1);
	ResetPerLifeKills(playerid);
	pKillCount[killerid][reason]++;

	pDeaths(playerid)++;
	pKills(killerid)++;

// Headshot
	if(head)
	{
		pHeadShot(killerid)++;
		GiveXP(killerid, 5, "Headshot!");
	}

// Avenger
	if( ((GetTickCount()-tick_LastKill[playerid])<=MAX_AVEN_TIME) && (LastKilled[playerid]!=killerid) )GiveXP(killerid, 3, "Avenged");

// Streaks
	pStreak(playerid)++;
	if(pStreak(playerid)>=3)GameMsgF(BLUE, "%s Ended %s's Streak of %d", GetName(killerid), GetName(playerid), pStreak(playerid));
	if(pStreak(playerid)>pInfo[killerid][pI_HighStreak])
	{
		pInfo[killerid][pI_HighStreak]=pStreak(playerid);
		if(pStreak(playerid)>3)msg(playerid, BLUE, "You have beaten your highest Killchain!");
	}

// Assists
	if( (PlayerShotBy[playerid]!=killerid) && (PlayerShotBy[playerid]!=FreeID) && (pTeam(PlayerShotBy[killerid])!=pTeam(playerid)) )
	{
		GiveXP(PlayerShotBy[playerid], 3, "assist");
		PlayerShotBy[playerid]=FreeID;
	}
	
// Combo
	if(GetTickCount()-tick_LastKill[killerid]<2000)
	{
		pDM_Data[killerid][Combo]++;
	    if(pDM_Data[killerid][Combo]>1)
	    {
			new sComboInfo[10];
			format(sComboInfo, 10, "combo x%d", pDM_Data[killerid][Combo]);
			GiveXP(killerid, (2*pDM_Data[killerid][Combo]), sComboInfo);
			msgF(killerid, WHITE, "** combo: %d tick: %d", pDM_Data[killerid][Combo], GetTickCount()-tick_LastKill[killerid]);
		}
	}
	
// Weapon Type
	switch(reason)
	{
		case 0:
		{
			GiveXP(killerid, 10, "Beatdown");
			pKillCount[killerid][fist]++;
            GiveAward(killerid, fist);
			GameMsgF(LGREEN, "%s Has Won The 'Beatdown' Award, Killing Someone with Fists", GetName(killerid));
		}
		case 34:
		{
		    new Float:KillDistance = GetPlayerDist3D(killerid, playerid);
			if(KillDistance >= MAX_DIST_BONUS)
			{
				GiveXP(killerid, floatround(KillDistance/10), "Marksman");
				GameMsgF(LGREEN, "%s Has Won The 'Longrange' Award for Sniping someone %f meters away!", GetName(killerid), GetPlayerDist3D(killerid, playerid));
                GiveAward(killerid, sniper_l);
			}
		}
		default:GiveXP(killerid, 5, "kill");
	}
}
RankCheck(playerid)
{
	new i=1;
	while(i <= MAX_RANK)
	{
		if( (pExp(playerid) >= RequiredExp[i]) && (pRank(playerid) == i-1) )
		{
			pRank(playerid) = i;
			LevelUpWeaponSkills(playerid, pRank(playerid)*100);
			msgF(playerid, LGREEN, "You Just Ranked Up! You are now rank %d", pRank(playerid));
			break;
		}
		i++;
	}
	if(pRank(playerid) > MAX_RANK) pRank(playerid)=MAX_RANK;
	if( (RequiredExp[pRank(playerid)+1]-pExp(playerid)) < 1)msg(playerid, RED, "Your Exp statistic Has corrupted, please use /bug, type \"[EXP-PROBLEM]\" and your name");
}
AwardUpdate(playerid, type)
{
	new pFile[40];
	pFile=GetFile(playerid);
	if(type==0)
	{
		for(new w;w<MAX_WEAPON;w++)
		{
		    for(new a;a<sizeof(AwardData);a++)
		    {
		    	if(w==AwardData[a][wepid])if(pKillCount[playerid][w]==AwardData[a][awdReq])GiveAwardEx(playerid, a);
		    }
		}
	}
	else if(type==1)
	{
	}
}

GiveAwardEx(playerid, awd)
{
	GameMsgF(LGREEN, "%s Has Won The '%s' Award, Killing %d players with a %s in one life", GetName(playerid), AwardData[awd][awdName], AwardData[awd][awdReq], WepData[AwardData[awd][wepid]][WepName]);
	GiveXP(playerid, AwardData[awd][awdRew], AwardData[awd][awdName]);
	GiveAward(playerid, awd);
}
TeamScoreUpdate()
{
	new score[48];
	if(DMmode==DM_MODE_TDM)
	{
	    if(ScoreLimit==0)format(score, 40, "TDM~n~ Raven: %d~n~   Valor: %d", TeamScore[Score][0], TeamScore[Score][1]);
	    else
	    {
			format(score, 48, "Score~n~ Raven: %d/%d~n~   Valor: %d/%d", TeamScore[Score][0], ScoreLimit, TeamScore[Score][1], ScoreLimit);
			if( (TeamScore[Score][0] == ScoreLimit) || (TeamScore[Score][1] == ScoreLimit) && (bServerGlobalSettings&DMstarted))EndRound();
		}
	}
	if(DMmode==DM_MODE_AD)
	{
		format(score, 48, "Tickets~n~ Attackers: %d", TeamScore[Ticket][!DefendingTeam]);
		if(TeamScore[Ticket][!DefendingTeam]==0)
		{
		    WinningTeam=DefendingTeam;
			EndRound();
		}
	}
	if(DMmode==DM_MODE_CTF)
	{
		format(score, 48, "Flags~n~ Raven: %d/%d~n~   Valor: %d/%d", TeamScore[Flags][0], FlagLimit, TeamScore[Flags][1], FlagLimit);
		if( (TeamScore[Flags][0] >= FlagLimit) || (TeamScore[Flags][1] >= FlagLimit) )EndRound();
	}
	if(DMmode==DM_MODE_CQS)
	{
		format(score, 48, "Tickets~n~ Raven: %d~n~   Valor: %d", TeamScore[Ticket][0], TeamScore[Ticket][1]);
		if( (TeamScore[Ticket][0] <= 0) || (TeamScore[Ticket][1] <= 0) )
		{
			for(new i;i<2;i++)if(TeamScore[Ticket][i]>0)WinningTeam=i;
			EndRound();
		}
	}
	TextDrawSetString(ScoreBox, score);

	if(DMmode!=DM_MODE_AD&&(bServerGlobalSettings&DMstarted))UpdateScoreStatus();
}
DeathmatchDataUpdate(playerid, killerid)
{
	if(DMmode==DM_MODE_AD)
	{
		if(bPlayerDeathmatchSettings[playerid]&CapturingADPoint)
		{
			bitFalse(bPlayerDeathmatchSettings[playerid], CapturingADPoint);
			HideProgressBarForPlayer(playerid, ADbar);
			if(GetPlayersCapturingAD() == 0)
			{
				PointCT=false;
			    ContinueMatchTime();
			}
			if(killerid!=INVALID_PLAYER_ID)GiveXP(killerid, 3, "Defensive Kill");
		}
		if(killerid!=INVALID_PLAYER_ID)
			if(bPlayerDeathmatchSettings[killerid]&CapturingADPoint)GiveXP(killerid, 3, "Offensive Kill");
	}
	if(DMmode==DM_MODE_CTF)
	{
		if(bPlayerDeathmatchSettings[playerid]&HasFlag)
		{
			bitFalse(bPlayerDeathmatchSettings[playerid], HasFlag);
			CtfFlag[poTeam(playerid)] = CreateDynamicPickup(CTF_FLAG_MODEL, 1, CtfPosF[poTeam(playerid)][0], CtfPosF[poTeam(playerid)][1], CtfPosF[poTeam(playerid)][2]);
			UpdateFlagIcons();
			GameMsgF(RED, "%s Dropped The Flag!", GetName(playerid));
			if(killerid!=INVALID_PLAYER_ID)GiveXP(killerid, 5, "Flag Denial");
		}
		if(killerid!=INVALID_PLAYER_ID)
			if(bPlayerDeathmatchSettings[killerid]&HasFlag)GiveXP(killerid, 3, "Protection");
	}
	if(DMmode==DM_MODE_CQS)
	{
		if(CapturingCP[playerid] != -1)
		{
			new CP = CapturingCP[playerid];
			CapturingCP[playerid] = -1;
		    if(GetPlayersCapturing(CP)==0)
		    {
				CPtimer[CP]=false;
				CPowner[CP]=-1;
			}
			if(killerid!=INVALID_PLAYER_ID)GiveXP(killerid, 10, "Defensive Kill");
		}
		if(killerid!=INVALID_PLAYER_ID)
		{
			if(CapturingCP[killerid] != -1)GiveXP(killerid, 3, "Offensive Kill");
		}
	}
}
ResetPerLifeKills(playerid)for(new i;i<MAX_WEAPON;i++)pKillCount[playerid][i]=0;
DropWep(playerid)
{
	new
		Float:PX, Float:PY, Float:PZ, Float:PA,
		pWep = GetPlayerWeapon(playerid),
		pAmmo = GetPlayerAmmo(playerid);
	GetPlayerPos(playerid, PX, PY, PZ);
	GetPlayerFacingAngle(playerid, PA);
	AddWeaponPickup(PX, PY, PZ, pWep, pAmmo, 90, 0, PA);
	return 1;
}
script_Deathmatch_WeaponChange(playerid, newweapon)
{
	if(GetWeaponType(newweapon)==-1||GetWeaponType(newweapon)==0||GetWeaponType(newweapon)==3)
	{
	    if(HasWeaponType(playerid, 2)!=-1)SetPlayerAttachedObject(playerid, PRIMARY_SLOT, WepData[HasWeaponType(playerid, 2)][WepModel], 1, 0.1, -0.1, 0.18, 0.0, 160.0, 0.0);
	    if(HasWeaponType(playerid, 1)!=-1)SetPlayerAttachedObject(playerid, SIDEARM_SLOT, WepData[HasWeaponType(playerid, 1)][WepModel], 8, 0.0, 0.0, 0.1, 270.0, 0.0);
	}
	if(GetWeaponType(newweapon)==1)
	{
	    RemovePlayerAttachedObject(playerid, SIDEARM_SLOT);
	    if(HasWeaponType(playerid, 2)!=-1)SetPlayerAttachedObject(playerid, PRIMARY_SLOT, WepData[HasWeaponType(playerid, 2)][WepModel], 1, 0.1, -0.1, 0.18, 0.0, 160.0, 0.0);
	}
	if(GetWeaponType(newweapon)==2)
	{
	    RemovePlayerAttachedObject(playerid, PRIMARY_SLOT);
	    if(HasWeaponType(playerid, 1)!=-1)SetPlayerAttachedObject(playerid, SIDEARM_SLOT, WepData[HasWeaponType(playerid, 1)][WepModel], 8, 0.0, 0.0, 0.1, 270.0, 0.0);
	}
}

script_Deathmatch_KeyChange(playerid, newkeys)
{
	if(newkeys == EQUIPMENT_KEY)
	{
		if(bDeathmatchSettings&EquipmentUsage && !IsPlayerInAnyVehicle(playerid) && (bPlayerGameSettings[playerid]&InDM) && !(bPlayerGameSettings[playerid]&UsingEquipment) && !(bPlayerDeathmatchSettings[playerid]&BleedingOut))
		{
			switch(pKit(playerid))
			{
				case KIT_ASSAULT:KitEquip_Assault(playerid);
				case KIT_MEDIC:KitEquip_Medic(playerid);
				case KIT_SNIPER:KitEquip_Sniper(playerid);
				case KIT_ENGINEER:KitEquip_Engineer(playerid);
			}
		}
	}
	if(newkeys & ACTION_KEY)
	{
		if(bPlayerDeathmatchSettings[playerid]&BleedingOut)
		{
		    if(BleedAttacker[playerid]==INVALID_PLAYER_ID)OnDeath(playerid);
		    else script_Deathmatch_OnPlayerKill(playerid, BleedAttacker[playerid], BleedReason[playerid]);
			ExitBleedOut(playerid);
		}
		for(new w;w<MAX_DM_WEP;w++)
		{
			if(IsPlayerInDynamicArea(playerid, WepSpr[w]))
			{
				ApplyAnimation(playerid, "bomber", "bom_Plant", 10.0, 1, 0, 0, 0, 1000);
				PlayerPickUpWeapon(playerid, w);
			}
		}
		for(new x;x<MAX_AMMO_CRATE;x++)
		{
			if(IsPlayerInRangeOfPoint(playerid, 2.0, SupplyPos[x][0], SupplyPos[x][1], SupplyPos[x][2]))
			{
			    if(bDeathmatchSettings&ArcadeMode)ShowArcadeWeaponList(playerid);
			    else
			    {
					if(GetTickCount() >= tick_AllowedAmmo[playerid])
					{
						ApplyAnimation(playerid, "bomber", "bom_Plant", 1.0, 1, 0, 0, 0, 2000);
						ReSupplyPlayer(playerid);
						PlayerLoop(p)
						{
							if(x==p+20)
							{
								SupplyCount[x]--;
								if(SupplyCount[x]==0)DestroySupplyCrate(x, playerid);
								if(playerid!=p)GiveXP(p, 10, "Supply");
							}
						}
						tick_AllowedAmmo[playerid]=GetTickCount()+30000;
					}
					else msg(playerid, RED, "You are not allowed to refill your ammo yet, please wait");
				}
				break;
			}
		}
	}
	if(newkeys & GEAR_KEY)
	{
		if(pGear(playerid)==g_Ghillie)
		{
			if(!(bPlayerDeathmatchSettings[playerid]&GearUse))
			{
				SetPlayerAttachedObject(playerid, GHILLIE_SLOT, 760, 1, _, _, _, 90, _, _);
				bitFalse(bPlayerDeathmatchSettings[playerid], GearUse);
			}
			else
			{
				RemovePlayerAttachedObject(playerid, GHILLIE_SLOT);
				bitFalse(bPlayerDeathmatchSettings[playerid], GearUse);
			}
		}
		if(pGear(playerid)==g_PlayDead)
		{
			ApplyAnimation(playerid, "ped", "die", 4.1, 0, 0, 0, 0, 0);
			bitFalse(bPlayerDeathmatchSettings[playerid], PlayingDead);
			bitFalse(bPlayerDeathmatchSettings[playerid], GearUse);
		}
	}


	if(newkeys == KEY_JUMP)
	{
		if( bPlayerGameSettings[playerid]&InLobby && bPlayerGameSettings[playerid]&ReadyForDM )
		{
			JoinLobby(playerid);
			if(bServerGlobalSettings&LobbyCountingDown)
			{
				bitFalse(bServerGlobalSettings, LobbyCountingDown);
				LobbyCountInt=MAX_LOBBY_COUNT;
				UpdateLobbyCount();
			}
		}
	}
	return 1;
}



script_Deathmatch_EnterArea(playerid, areaid)
{
	for(new i=0;i<MAX_MINES;i++)
	{
		if( (areaid==MineProx[i]) && (pTeam(playerid)!=pTeam(MineOwner[i])) && (GetPlayerSpecialAction(playerid)!=SPECIAL_ACTION_DUCK) )ExplodeMine(i);
		if(areaid==MineLoc[i]&&pTeam(playerid)!=pTeam(MineOwner[i])&&(bDeathmatchSettings&GearItemUsage&&pGear(playerid)==g_ProxDet))
		{
			GameTextForPlayer(playerid, "~r~Warning ~n~-~n~ Mine", 1000, 5);
			PlayerPlaySound(playerid, 1085, MinePos[i][0], MinePos[i][1], MinePos[i][2]);
		}
	}
	if(pKit(playerid)==KIT_MEDIC)PlayerLoop(i)if(areaid==PlayerProximity[i] && playerid!=i)ShowMsgBox(playerid, "Press ~g~"#TEXT_EQUIP_KEY" ~w~to revive player");
	for(new i=0;i<MAX_AMMO_CRATE;i++)if(areaid==SupplyArea[i])ShowMsgBox(playerid, "Press ~g~"#TEXT_ACTION_KEY" ~w~to refil Ammo");
	for(new i=0;i<MAX_DM_WEP;i++)
	{
		    if(areaid==WepSpr[i])
			{
			    new str[128],pWep,pAmmo;
			    for(new slot;slot<12;slot++)
				{
					GetPlayerWeaponData(playerid, slot, pWep, pAmmo);
					if(GetWeaponType(pWep)==GetWeaponType(WepId[i]) && pAmmo>0)
					{
						format(str, 128, "Press ~g~"#TEXT_ACTION_KEY" ~w~to swap ~b~%s ~w~for ~b~%s ~w~with ~y~%d ~w~ammo", WepData[pWep][WepName], WepData[WepId[i]][WepName], WepAmo[i]);
						ShowMsgBox(playerid, str);
						break;
					}
				}
			}
	}

	if(DMmode==DM_MODE_AD)
	{
		if(areaid == PointToCapture)
		{
			if( pTeam(playerid)!=DefendingTeam && IsPlayerInGame(playerid) )
			{
				bitTrue(bPlayerDeathmatchSettings[playerid], CapturingADPoint);
				if(MatchTimeLimit>0)PauseMatchTime();
				GameMsgF(BLUE, "%s Is capturing the point", GetName(playerid));

				if(GetPlayersCapturingAD() == 1)
				{
					PointCT=true;
					capturer=playerid;
				}
			}
			else ShowMsgBox(playerid, "This is the point you defend", 3000);
		}
	}
	else if(DMmode==DM_MODE_CQS)
	{
		for(new cp=0;cp<MAX_CP;cp++)
		{
			if(areaid == CPflag[cp])
			{
				if( CPowner[cp]!=pTeam(playerid) && IsPlayerInGame(playerid) )
				{
				    if(CPowner[cp]!=-1)CPfill[cp]=20;
				    else CPfill[cp]=0;
					if(GetPlayersCapturing(cp)==0)FirstToCapture[cp]=playerid;
					CapturingCP[playerid] = cp;
					CPtimer[cp]=true;

					ShowProgressBarForPlayer(playerid, CPbar[cp]);
					GameMsgF(ORANGE, "%s Is Capturing %s!", GetName(playerid), CPname[cp]);
				}
			}
		}
	}
	return 1;
}
script_Deathmatch_ExitArea(playerid, areaid)
{
	PlayerLoop(i)if(areaid==PlayerProximity[i])HideMsgBox(playerid);
	for(new i=0;i<MAX_AMMO_CRATE;i++)if(areaid==SupplyArea[i])HideMsgBox(playerid);
	for(new i=0;i<MAX_DM_WEP;i++)if(areaid==WepSpr[i])HideMsgBox(playerid);

	if(areaid == DMzone)GameTextForPlayer(playerid, "~w~get back to the fight!", 500, 4);

	if(DMmode==DM_MODE_AD)
	{
		if(areaid == PointToCapture)
		{
		    ContinueMatchTime();
		    bitFalse(bPlayerDeathmatchSettings[playerid], CapturingADPoint);
			if(GetPlayersCapturingAD() == 0) PointCT=false;
			HideProgressBarForPlayer(playerid, ADbar);
		}
	}
	if(DMmode==DM_MODE_CQS)
	{
		for(new cp=0;cp<MAX_CP;cp++)
		{
		    if(areaid == CPflag[cp])
		    {
				CapturingCP[playerid] = -1;
				if(GetPlayersCapturing(cp) == 0)CPtimer[cp]=false;
				HideProgressBarForPlayer(playerid, CPbar[cp]);
			}
		}
	}
	return 1;
}
UpdateFlagIcons()
{
	new
		TeamHasFlag=-1;

	PlayerLoop(i)
	{
		if(bPlayerDeathmatchSettings[i]&HasFlag)
		{
			TeamHasFlag=pTeam(i);
			break;
		}
	}
	if(TeamHasFlag!=-1)
	{
	    PlayerLoop(i)if(pTeam(i)==TeamHasFlag)
	    {
			SetPlayerMapIcon(i, CtfIcon, CtfPosF[pTeam(i)][0], CtfPosF[pTeam(i)][1], CtfPosF[pTeam(i)][2], 0, BLUE, MAPICON_GLOBAL);
		}
	}
	else
	{
	    PlayerLoop(i)
	    {
			SetPlayerMapIcon(i, CtfIcon, CtfPosF[poTeam(i)][0], CtfPosF[poTeam(i)][1], CtfPosF[poTeam(i)][2], 0, RED, MAPICON_GLOBAL);
		}
	}
}

script_Deathmatch_handleDialog(playerid, dialogid, response, listitem, inputtext[])
{
	if(dialogid == d_RegionSelect)
	{
		if(response)
		{
		    if(listitem==MAX_REGION)
			{
				TogglePlayerControllable(playerid, true);
				DMhost = -1;
			}
		    else
		    {
				ShowPlayerDialog(playerid, d_RegionMaps, DIALOG_STYLE_LIST, RegionNames[listitem], RegionMaps[listitem], "Accept", "Info");
				SelectedRegion=listitem;
			}
		}
		else FormatRegionInfo(playerid, listitem);
		return 1;
	}
	if(dialogid == d_RegionInfo)
	{
		ShowPlayerDialog(playerid, d_RegionSelect, DIALOG_STYLE_LIST, "Choose a map style category", RegionMenu, "Accept", "Info");
		return 1;
	}

	if(dialogid == d_RegionMaps)
	{
	    for(new m;m<MAX_MAPS;m++)
	    {
	    	if(MapRegion[m] == SelectedRegion && RegionItems[m] == listitem)
	    	{
				if(response)
				{
	    		    DMmap=m;
					FormatModeSelect(playerid);
					return 1;
				}
				else
				{
					FormatMapInfo(playerid, m);
					return 1;
				}
	    	}
	    }
		ShowPlayerDialog(playerid, d_RegionSelect, DIALOG_STYLE_LIST, "Choose a map style category", RegionMenu, "Accept", "Info");
	}
	if(dialogid == d_MapInfo)
	{
		ShowPlayerDialog(playerid, d_RegionMaps, DIALOG_STYLE_LIST, RegionNames[SelectedRegion], RegionMaps[SelectedRegion], "Accept", "Info");
		return 1;
	}

	if(dialogid == d_ModeSelect)
	{
		for(new i;i<MAX_MODE;i++)
		{
			if(!strcmp(inputtext, ModeNames[i], false, strlen(ModeNames[i])))
			{
				if(response)
				{
					DMmode=i;
					ResetDMSettings();
					FormatSettingsMenu(playerid);
					return 1;
				}
				else FormatGamemodeInfo(playerid, i);
			}
		}
		if(!strcmp(inputtext, "Back"))return ShowPlayerDialog(playerid, d_RegionMaps, DIALOG_STYLE_LIST, RegionNames[SelectedRegion], RegionMaps[SelectedRegion], "Accept", "Info");
	}
	if(dialogid == d_ModeInfo)
	{
		FormatModeSelect(playerid);
		return 1;
	}

	if(dialogid == d_Settings)
	{
	    if(response)
	    {
			switch(listitem)
			{
				case 0: // Max Players
				{
					ShowPlayerDialog(playerid, d_MaxP, DIALOG_STYLE_INPUT, "Max Players", "Enter the Maximum players for match", "Apply", "Clear");
				}
				case 1: // Min Players
				{
					ShowPlayerDialog(playerid, d_MinP, DIALOG_STYLE_INPUT, "Min Players", "Enter the Minimum players for match", "Apply", "Clear");
				}
				case 2: // Score Limit
				{
					if(DMmode==DM_MODE_TDM)ShowPlayerDialog(playerid, d_Scorelim, DIALOG_STYLE_INPUT, "Score Limit", DIALOGTEXT_SCORLIM, "Apply", "Clear");
					if(DMmode==DM_MODE_AD)ShowPlayerDialog(playerid, d_Ticketlim, DIALOG_STYLE_INPUT, "Attackers Tickets", DIALOGTEXT_TICKLIM, "Apply", "Clear");
					if(DMmode==DM_MODE_CTF)ShowPlayerDialog(playerid, d_Flaglim, DIALOG_STYLE_INPUT, "Flag Limit", DIALOGTEXT_FLAGLIM, "Apply", "Clear");
					if(DMmode==DM_MODE_CQS)ShowPlayerDialog(playerid, d_Forcelim, DIALOG_STYLE_INPUT, "Reinforcement Tickets", DIALOGTEXT_FORCLIM , "Apply", "Clear");
				}
				case 3: // Time Limit
				{
					ShowPlayerDialog(playerid, d_Matchtime, DIALOG_STYLE_INPUT, "Match Time Limit", "Enter the Match Time in minutes", "Apply", "Clear");
				}
				case 4: // Hardcore
				{
				    if(bDeathmatchSettings&Hardcore)
					{
						bitFalse(bDeathmatchSettings, Hardcore);
						GlobalMaxHP=MAX_HEALTH;
					}
				    else
					{
						bitTrue(bDeathmatchSettings, Hardcore);
						GlobalMaxHP=MAX_HEALTH*0.6;
					}
				    FormatSettingsMenu(playerid);
				}
				case 5: // Arcade Mode
				{
				    if(bDeathmatchSettings&ArcadeMode)bitFalse(bDeathmatchSettings, ArcadeMode);
				    else bitTrue(bDeathmatchSettings, ArcadeMode);
				    FormatSettingsMenu(playerid);
				}
				case 6: // Vehicles
				{
				    if(bDeathmatchSettings&Vehicles)bitFalse(bDeathmatchSettings, Vehicles);
				    else bitTrue(bDeathmatchSettings, Vehicles);
				    FormatSettingsMenu(playerid);
				}
				case 7: // Headshot Instant Kill
				{
				    if(bDeathmatchSettings&InstaHS)bitFalse(bDeathmatchSettings, InstaHS);
				    else bitTrue(bDeathmatchSettings, InstaHS);
				    FormatSettingsMenu(playerid);
				}
				case 8: // Revive System
				{
				    if(bDeathmatchSettings&Revive)bitFalse(bDeathmatchSettings, Revive);
				    else bitTrue(bDeathmatchSettings, Revive);
				    FormatSettingsMenu(playerid);
				}
				case 9: // Friendly Fire
				{
				    if(bDeathmatchSettings&FriendlyFire)bitFalse(bDeathmatchSettings, FriendlyFire);
				    else bitTrue(bDeathmatchSettings, FriendlyFire);
				    FormatSettingsMenu(playerid);
				}
				case 10: // MSU
				{
				    if(bDeathmatchSettings&MobSpawnUnit)bitFalse(bDeathmatchSettings, MobSpawnUnit);
				    else bitTrue(bDeathmatchSettings, MobSpawnUnit);
				    FormatSettingsMenu(playerid);
				}
				case 11: // Equipment
				{
				    if(bDeathmatchSettings&EquipmentUsage)bitFalse(bDeathmatchSettings, EquipmentUsage);
				    else bitTrue(bDeathmatchSettings, EquipmentUsage);
				    FormatSettingsMenu(playerid);
				}
				case 12: // Gear
				{
				    if(bDeathmatchSettings&GearItemUsage)bitFalse(bDeathmatchSettings, GearItemUsage);
				    else bitTrue(bDeathmatchSettings, GearItemUsage);
				    FormatSettingsMenu(playerid);
				}
				case 13: // Equal Weps
				{
				    if(bDeathmatchSettings&EqualWeapons)bitFalse(bDeathmatchSettings, EqualWeapons);
				    else bitTrue(bDeathmatchSettings, EqualWeapons);
				    FormatSettingsMenu(playerid);
				}
				case 14: // Team Talk
				{
				    if(bDeathmatchSettings&TeamTalk)bitFalse(bDeathmatchSettings, TeamTalk);
				    else bitTrue(bDeathmatchSettings, TeamTalk);
				    FormatSettingsMenu(playerid);
				}
				case 15: // Team Balance
				{
				    if(bDeathmatchSettings&TeamBalance)bitFalse(bDeathmatchSettings, TeamBalance);
				    else bitTrue(bDeathmatchSettings, TeamBalance);
				    FormatSettingsMenu(playerid);
				}
				case 16: // Start DM
				{
					LoadDeathmatch();
					msgaF(GOLD, "%s Is hosting a Deathmatch, "#C_BLUE"Type /joindm to join", GetName(playerid));
					msg(playerid, YELLOW, "**When everyone is ready the deathmatch will start");
					JoinDeathMatch(playerid);
				}
				case 17: // Cancel DM
				{
					ResetDMVariables();
				    TogglePlayerControllable(playerid, true);
				}
				case 18: // Reset Settings
				{
				    ResetDMSettings();
				    FormatSettingsMenu(playerid);
				}
		    }
		}
		else
		{
			switch(listitem)
			{
				case 0:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Max Players",			"Maximum players that can be in a deathmatch", "Back", "");
				case 1:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Min Players",			"Minimum amount of players that have to be in the lobby before the deathmatch starts", "Back", "");
				case 2:
				{
				    if(DMmode==DM_MODE_TDM)ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Score Limit",			"Amount of kills teams need to win the game.\n0 for unlimited.", "Back", "");
				    if(DMmode==DM_MODE_AD)ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Attackers Tickets",		"Amount of reinforcement tickets attackers get,\nteam loses a ticket when a player of that team dies.\ndefenders get unlimited.", "Back", "");
				    if(DMmode==DM_MODE_CTF)ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Flag Limit",			"Amount of flags teams need to capture to win the game.", "Back", "");
				    if(DMmode==DM_MODE_CQS)ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Reinforcement Tickets",	"Reinforcement Tickets each team is allocated at the start of the game.\nTeam loses a ticket when a player of that team dies.", "Back", "");
				}
				case 3:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Time Limit",			"Amount of time before the game ends.\n 0 for unlimited.", "Back", "");
				case 4:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Low Health",			"1/3 of the normal amount of health is given to players.", "Back", "");
				case 5:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Arcade Mode",			"(In development)", "Back", "");
				case 6:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Vehicles",				"Toggle vehicles on the map or not.\nNote: Not all maps have vehicles.", "Back", "");
				case 7:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Headshot Kill",			"Players die instantly when shot in the head.", "Back", "");
				case 8:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Reviving Players",		"Toggle whether players can be revived after being knocked down.\nA player is knocked down if their health is very low but not 0.", "Back", "");
				case 9:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Friendly Fire",			"Toggle whether players can be damaged by members of their own team.", "Back", "");
				case 10:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "MSU (Conquest)",		"Toggle whether Mobile Spawn Units spawn on Conquest maps.\nThese are vehicles that can be spawned on like Control Points.", "Back", "");
				case 11:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Equipment Usage",		"Toggle whether players can use Equipment.", "Back", "");
				case 12:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Gear Items",			"Toggle whether players can use Gear Items.", "Back", "");
				case 13:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Equal Weapons",		"Toggle whether all players have the same weapons in each class instead of using unlocked weapons.", "Back", "");
				case 14:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Team Talk",			"Toggle whether players can only communicate with their team\nPlayers can talk to both teams with /g [message]", "Back", "");
				case 15:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Team Balance",			"Toggle whether players can't join a team if it has more players that the other team.", "Back", "");
				case 16:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Start Deathmatch",		"Start the deathmatch with current settings.", "Back", "");
				case 17:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Cancel Deathmatch",	"Cancel all settings and return to freeroam.", "Back", "");
				case 18:ShowPlayerDialog(playerid, d_SettingsInfo, DIALOG_STYLE_MSGBOX, "Reset Settings",		"Reset settings to default values.", "Back", "");
			}
		}
	}
	if(dialogid == d_SettingsInfo)
	{
		FormatSettingsMenu(playerid);
		return 1;
	}

	if(dialogid == d_Scorelim)
	{
	    new value = strval(inputtext);
		if( (value<SCORLIM_MIN) || (value>SCORLIM_MAX) || (!response) )ShowPlayerDialog(playerid, d_Scorelim, DIALOG_STYLE_INPUT, "Score Limit", DIALOGTEXT_SCORLIM, "Apply", "Clear");
		else
		{
			ScoreLimit = value;
		    FormatSettingsMenu(playerid);
		}
	}
	if(dialogid == d_Ticketlim)
	{
	    new value = strval(inputtext);
		if( (value<TICKLIM_MIN) || (value>TICKLIM_MAX) || (!response) )ShowPlayerDialog(playerid, d_Ticketlim, DIALOG_STYLE_INPUT, "Attackers Tickets", DIALOGTEXT_TICKLIM, "Apply", "Clear");
		else
		{
			TeamScore[Ticket][!DefendingTeam] = value;
		    FormatSettingsMenu(playerid);
		}
	}
	if(dialogid == d_Flaglim)
	{
	    new value = strval(inputtext);
		if( (value<FLAGLIM_MIN) || (value>FLAGLIM_MAX) || (!response) )ShowPlayerDialog(playerid, d_Flaglim, DIALOG_STYLE_INPUT, "Score Limit", DIALOGTEXT_FLAGLIM, "Apply", "Clear");
		else
		{
			FlagLimit = value;
		    FormatSettingsMenu(playerid);
		}
	}
	if(dialogid == d_Forcelim)
	{
	    new value = strval(inputtext);
		if( (value<FORCLIM_MIN) || (value>FORCLIM_MAX) || (!response) )ShowPlayerDialog(playerid, d_Forcelim, DIALOG_STYLE_INPUT, "Reinforcement Limit", DIALOGTEXT_FORCLIM, "Apply", "Clear");
		else
		{
			TeamScore[Ticket][1] = value;
			TeamScore[Ticket][0] = value;
		    FormatSettingsMenu(playerid);
		}
	}

	if(dialogid == d_Matchtime)
	{
	    new value = strval(inputtext);
		if( (value<MATCHTIME_MIN) || (value>MATCHTIME_MAX) || (!response) )ShowPlayerDialog(playerid, d_Matchtime, DIALOG_STYLE_INPUT, "Match Time Limit", DIALOGTEXT_MATCHTIME, "Apply", "Clear");
		else
		{
			MatchTimeLimit = strval(inputtext);
		    FormatSettingsMenu(playerid);
		}
	}
	if(dialogid == d_MaxP)
	{
		if(strval(inputtext) < 2 || strval(inputtext) > 10)
		{
			msg(playerid, LGREEN, "Above 2 and below 10 please");
			ShowPlayerDialog(playerid, d_MaxP, DIALOG_STYLE_INPUT, "Max Players", DIALOGTEXT_MAXPLAYER, "Apply", "Clear");
		}
		else
		{
			DMmaxP = strval(inputtext);
			FormatSettingsMenu(playerid);
		}
		if(!response)ShowPlayerDialog(playerid, d_MaxP, DIALOG_STYLE_INPUT, "Max Players", DIALOGTEXT_MAXPLAYER, "Apply", "Clear");
	}
	if(dialogid == d_MinP)
	{
		if(strval(inputtext) < 2 || strval(inputtext) > 10)
		{
			msg(playerid, LGREEN, "Above 2 and below 10 please");
			ShowPlayerDialog(playerid, d_MinP, DIALOG_STYLE_INPUT, "Min Players", DIALOGTEXT_MINPLAYER, "Apply", "Clear");
		}
		else
		{
			DMminP = strval(inputtext);
			msgF(playerid, YELLOW, "Min Players Set To %d", DMminP);
			FormatSettingsMenu(playerid);
		}
		if(!response)ShowPlayerDialog(playerid, d_MinP, DIALOG_STYLE_INPUT, "Min Players", DIALOGTEXT_MINPLAYER, "Apply", "Clear");
	}




	if(dialogid==d_Gearselect)
	{
		pGear(playerid)=listitem;

		if(response)ShowMenuForPlayer(LobbyMenu, playerid);
		else ShowPlayerDialog(playerid, d_Gearinfo, DIALOG_STYLE_MSGBOX, GearName[listitem], GearInfo[listitem], "Back", "");
	}
	if(dialogid==d_Gearinfo)
	{
		FormatGearMenu(playerid);
	}


	if(dialogid==d_Spawnpoint)
	{
	    if(listitem<4)
	    {
			if(CPowner[listitem]==pTeam(playerid))
			{
			    TogglePlayerSpectating(playerid, false);
				SetPlayerCameraPos(playerid, CPOfSet[listitem][0], CPOfSet[listitem][1], CPOfSet[listitem][2]);
				SetPlayerCameraLookAt(playerid, CPpoint[listitem][0], CPpoint[listitem][1], CPpoint[listitem][2]);
				SetPlayerPos(playerid, CPpoint[listitem][0], CPpoint[listitem][1], CPpoint[listitem][2]-1.0);
			    if(!response)
			    {
					pSpawnPoint[playerid][0]=CPpoint[listitem][0],
					pSpawnPoint[playerid][1]=CPpoint[listitem][1],
					pSpawnPoint[playerid][2]=CPpoint[listitem][2];
					ShowMenuForPlayer(LobbyMenu, playerid);
				}
				else FormatSpawnMenu(playerid);
			}
			else
			{
				ShowMsgBox(playerid, "You haven't ~r~captured ~w~this ~y~command post ~w~yet", 3000);
				FormatSpawnMenu(playerid);
			    TogglePlayerSpectating(playerid, false);
			}
		}
		else
		{
		    if(MSUactive[pTeam(playerid)])
		    {
		        TogglePlayerSpectating(playerid, true);
		        PlayerSpectateVehicle(playerid, MSU_VehicleID[pTeam(playerid)]);
		        if(!response)
		        {
		            new Float:vPos[4];
		            GetVehiclePos(MSU_VehicleID[pTeam(playerid)], vPos[0], vPos[1], vPos[2]);
		            GetVehicleZAngle(MSU_VehicleID[pTeam(playerid)], vPos[3]);
		            GetXYFromAngle(vPos[0], vPos[1], vPos[3], -4);
					pSpawnPoint[playerid][0]=vPos[0],
					pSpawnPoint[playerid][1]=vPos[1],
					pSpawnPoint[playerid][2]=vPos[2];
					ShowMenuForPlayer(LobbyMenu, playerid);
		        }
		        else FormatSpawnMenu(playerid);
		    }
		    else
			{
				msg(playerid, RED, "The Mobile Spawn Unit has been destroyed");
				FormatSpawnMenu(playerid);
		    	TogglePlayerSpectating(playerid, false);
			}
		}
	}


	if(dialogid == d_KitInfo)ShowMenuForPlayer(KitSelect, playerid);
	if(dialogid == d_ArcadeWeapons)
	{
	    if(response)ShowArcadeWeaponOptions(playerid, listitem);
	    else return 0;
	}
	if(dialogid == d_ArcadeOptions)
	{
	    if(response)
	    {
			new HasWeapon, item = SelectedItem[playerid], current_wepid, current_ammo;
			GetPlayerWeaponData(playerid, WepData[ ArcadeWepData[item][0] ][GtaSlot], current_wepid, current_ammo);
			if(current_wepid == ArcadeWepData[item][0])HasWeapon=1;
	        if(listitem==0)
	        {
	            if(HasWeapon)
				{
					msg(playerid, RED, "You already have that weapon, buy some ammo instead");
					ShowArcadeWeaponOptions(playerid, item);
				}
				else
				{
				    if(GetPlayerMoney(playerid)>=ArcadeWepData[item][1])
				    {
				        GivePlayerMoney(playerid, -ArcadeWepData[item][1]);
				        GivePlayerWeapon(playerid, ArcadeWepData[item][0], WepData[ArcadeWepData[item][0]][MagSize]*2);
				        msg(playerid, YELLOW, "You got 2 free Mags of ammo! Be sure to come again soon!");
				        ShowArcadeWeaponOptions(playerid, item);
				    }
				    else
				    {
						msg(playerid, RED, "You can't afford that! Kill some more people!");
						ShowArcadeWeaponOptions(playerid, item);
				    }
				}
	        }
	        else if(listitem==1)
	        {
	            if(HasWeapon)
				{
				    if(GetPlayerMoney(playerid)>=ArcadeWepData[item][2])
				    {
				        GivePlayerMoney(playerid, -ArcadeWepData[item][2]);
				        GivePlayerWeapon(playerid, ArcadeWepData[item][0], WepData[ArcadeWepData[item][0]][MagSize]);
				        msg(playerid, YELLOW, "Purchased 1 Mag of ammo");
				        ShowArcadeWeaponOptions(playerid, item);
				    }
				    else
				    {
						msg(playerid, RED, "You can't afford that! Kill some more people!");
						ShowArcadeWeaponOptions(playerid, item);
				    }
				}
				else
				{
					msg(playerid, RED, "You need to buy the weapon before you buy ammo");
					ShowArcadeWeaponOptions(playerid, item);
				}
	        }
	    }
	    else ShowArcadeWeaponList(playerid);
	}
	return 1;
}


ShowArcadeWeaponList(playerid)
{
	new
		tmpstr[30],
		str[30*sizeof(ArcadeWepData)];

	for(new x;x<sizeof ArcadeWepData;x++)
	{
	    format(tmpstr, 30, "%s\n", WepData[ArcadeWepData[x][0]][WepName]);
	    strcat(str, tmpstr);
	}
	ShowPlayerDialog(playerid, d_ArcadeWeapons, DIALOG_STYLE_LIST, "Buy Weapons Here", str, "Options", "Close");
}
ShowArcadeWeaponOptions(playerid, item)
{
	new str[256];
	SelectedItem[playerid]=item;
	format(str, 256, "$%d\tBuy Weapon\n$%d\t%d Ammo Rounds", ArcadeWepData[item][1], ArcadeWepData[item][2], WepData[ArcadeWepData[item][0]][MagSize]);
	ShowPlayerDialog(playerid, d_ArcadeOptions, DIALOG_STYLE_LIST, "Weapon Options", str, "Buy", "Back");
}


script_Deathmatch_MenuRow(playerid, row, Menu:pMenu)
{
	if(pMenu == KitSelect)
	{
	    if(row==2)
	    {
			switch(DMmap)
			{
			    case 6, 9, 11, 13, 18, 23:
			    {
				    msgF(playerid, RED, "The Sniper class is disabled on the map %s", MapNames[DMmap]);
				    ShowMenuForPlayer(KitSelect, playerid);
			    }
			    default:
				{
					pKit(playerid)=2;
					ShowMenuForPlayer(LobbyMenu, playerid);
				}
			}
	    }
	    else if(row==4)FormatKitInfo(playerid);
	    else
		{
			pKit(playerid)=row;
			ShowMenuForPlayer(LobbyMenu, playerid);
		}
	}

	if(pMenu == TeamSelect)
	{
		new
			t0 = GetPlayersInTeam(0),
			t1 = GetPlayersInTeam(1);
		switch(row)
		{
			case 0:
			{
				if(t0>t1&&bDeathmatchSettings&TeamBalance)
				{
					msg(playerid, ORANGE, "This team is full");
					ShowMenuForPlayer(TeamSelect, playerid);
				}
				else
				{
					SetPlayerToTeam(playerid, 0);
					if(!(bPlayerGameSettings[playerid]&FirstSpawn))DMspawn(playerid);
					else ShowMenuForPlayer(LobbyMenu, playerid);
					GameMsgF(GREEN, "%s Has Joined The Raven Team", GetName(playerid));
					FormatLobbyInfoForAll();
				}
			}
			case 1:
			{
				if(t1>t0&&bDeathmatchSettings&TeamBalance)
				{
					msg(playerid, ORANGE, "This team is full");
					ShowMenuForPlayer(TeamSelect, playerid);
				}
				else
				{
					SetPlayerToTeam(playerid, 1);
					if(!(bPlayerGameSettings[playerid]&FirstSpawn))DMspawn(playerid);
					else ShowMenuForPlayer(LobbyMenu, playerid);
					GameMsgF(GREEN, "%s Has Joined The Valor Team", GetName(playerid));
					FormatLobbyInfoForAll();
				}
			}
		}
	}
	if(pMenu == LobbyMenu)
	{
	    switch(row)
	    {
			case 0:
			{
				ShowMenuForPlayer(TeamSelect, playerid);
				bitTrue(bPlayerGameSettings[playerid], FirstSpawn);
				pTeam(playerid) = 3;
			}
			case 1:
	        {
	            ShowMenuForPlayer(KitSelect, playerid);
				bitTrue(bPlayerGameSettings[playerid], FirstSpawn);
	        }
			case 2:
			{
				if(bDeathmatchSettings&GearItemUsage)FormatGearMenu(playerid);
				else
				{
					msg(playerid, RED, "Gear Items are disabled");
			    	ShowMenuForPlayer(LobbyMenu, playerid);
				}
			}
	        case 3:
	        {
	            if(DMmode==DM_MODE_CQS)FormatSpawnMenu(playerid);
	            else
	            {
	                msg(playerid, RED, "Only available in Conquest gamemodes");
	                ShowMenuForPlayer(LobbyMenu, playerid);
	            }
	        }
	        case 4:
	        {
				msg(playerid, RED, "This feature is not active yet");
				ShowMenuForPlayer(LobbyMenu, playerid);

	        }
	        case 5:
	        {
				SetPlayerToSpectate(playerid, true);
				msg(playerid, RED, "This feature is not active yet");
				ShowMenuForPlayer(LobbyMenu, playerid);
	        }
	        case 6:
	        {
				JoinQueue(playerid);
				HideMenuForPlayer(LobbyMenu, playerid);
				if(!(bServerGlobalSettings&DMstarted))
				{
					new
						iReadyPlayers,
						iPlayersInLobby = GetPlayersInLobby();
					PlayerLoop(i)if(bPlayerGameSettings[i]&ReadyForDM)iReadyPlayers++;
					if( (iReadyPlayers==iPlayersInLobby) && (iPlayersInLobby>= 1) )//DMminP) )
					{
						LobbyCountInt=MAX_LOBBY_COUNT;
						bitTrue(bServerGlobalSettings, LobbyCountingDown);
					}
				}
	        }

	    }
	}
}

ValidMapMode(map, mode)
{
	if(MapModes[map]&mode)return 1;
	return 0;
}
FormatLobbyInfo(playerid)
{
	HideMsgBox(playerid);
	new str[290];

	format(str, 290,
	"~y~~k~~PED_JUMPING~ ~w~to show lobby menu~n~~n~\
	Team: ~b~%s~n~\
	~w~Kit: ~b~%s~n~\
	~w~Gear: ~b~%s~n~~n~\
	~w~Raven: ~g~%d~n~\
	~w~Valor: ~g~%d~n~~n~\
	~w~Map: ~r~%s~n~\
	~w~Mode: ~r~%s~n~\
	~w~Map Author: ~r~%s",
	TeamName[pTeam(playerid)],
	KitName[pKit(playerid)],
	GearName[pGear(playerid)],
	GetPlayersInTeam(0),
	GetPlayersInTeam(1),
	MapNames[DMmap],
	ModeABVs[DMmode],
	MapAuthor);

	ShowMsgBox(playerid, str);
}
FormatLobbyInfoForAll()PlayerLoop(i)if(bPlayerGameSettings[i]&InLobby&&bPlayerGameSettings[i]&ReadyForDM)FormatLobbyInfo(i);


FormatModeSelect(playerid)
{
	new str[256], tmpstr[20], infostr[64];
	for(new i=1, x=(MAX_MODE-1);i<=0b1000;i<<=1,x--)
	{
		if(ValidMapMode(DMmap, i))
		{
		    format(tmpstr, 20, "%s\n", ModeNames[x]);
		    strcat(str, tmpstr);
		}
	}
	strcat(str, "Back");
	format(infostr, 64, "Available Gamemodes For "#C_BLUE"%s", MapNames[DMmap]);
	ShowPlayerDialog(playerid, d_ModeSelect, DIALOG_STYLE_LIST, infostr, str, "Accept", "Info");
	return 1;
}
FormatRegionInfo(playerid, region)
{
	new szInfo[148];
	switch(region)
	{
	    case 0:szInfo="Built up areas with tight alley ways, side streets and open plazas perfect for ambushing and sniping.";
	    case 1:szInfo="Woodlands, fields and overgrown farms, lots of bushes and trees to sneak around in with the Ghillie suit gear item.";
	    case 2:szInfo="Open areas, rocks, desert villages but not a lot of bushes to hide in, ideal for assaults, but hiding my prove difficult.";
	    case 3:szInfo="Islands, docks and desolate refuges, attack vehicles are boats and the camouflage is the sea, brilliant for sniping and complex tactical planning.";
	    case 4:szInfo="Maps that are based around the original San Andreas towns and areas. There are modded map additions to most of these maps.";
	}
	ShowPlayerDialog(playerid, d_RegionInfo, DIALOG_STYLE_MSGBOX, RegionNames[region], szInfo, "Back", "");
}
FormatMapInfo(playerid, map)
{
	new szInfo[256];
	format(szInfo, 256, ""#C_YELLOW"Size:\t"#C_WHITE"%s\n\n"#C_YELLOW"Kit:\t"#C_WHITE"%s\n\n"#C_YELLOW"Intel:\n\t"#C_WHITE"%s", MapInfo_Size[map], MapInfo_Kit[map], MapInfo_Bio[map]);
	ShowPlayerDialog(playerid, d_MapInfo, DIALOG_STYLE_MSGBOX, MapNames[map], szInfo, "Back", "");
	return 1;
}
FormatGamemodeInfo(playerid, mode)
{
	new szInfo[232];
	switch(mode)
	{
	    case 0:szInfo="In this gamemode the objective is simply reach the score limit, do this by killing members of the enemy team.";
	    case 1:szInfo="One team defends a position and the other team has to capture it by staying in the area for long enough.\nLarger maps have three points to capture one after another.";
	    case 2:szInfo="Each team has a flag in their base, players have to pick up the enemy's flag and return it to their base to score points for their team.";
	    case 3:szInfo="Each map has 4 strategic points which teams aim to capture.\nEach team has a ticket count which depletes every time a team member is killed.\nIf your team captures all the positions or the enemy has no tickets left, your team wins.";
	}
	ShowPlayerDialog(playerid, d_ModeInfo, DIALOG_STYLE_MSGBOX, ModeNames[mode], szInfo, "Back", "");
}

FormatSettingsMenu(playerid)
{
	new
		StdSettings[76],
		BoolSettings[247],
		OtherOptions[50],
		FullString[372],

		ScoreLim,
		bSet[12][9];

	if(DMmode==DM_MODE_TDM)ScoreLim=ScoreLimit;
	if(DMmode==DM_MODE_AD)ScoreLim=TeamScore[Ticket][!DefendingTeam];
	if(DMmode==DM_MODE_CTF)ScoreLim=FlagLimit;
	if(DMmode==DM_MODE_CQS)ScoreLim=TeamScore[Ticket][0];

	bSet[0]=BoolToString((bDeathmatchSettings&Hardcore), 2);
	bSet[1]=BoolToString((bDeathmatchSettings&ArcadeMode), 2);
	bSet[2]=BoolToString((bDeathmatchSettings&Vehicles), 2);
	bSet[3]=BoolToString((bDeathmatchSettings&InstaHS), 2);
	bSet[4]=BoolToString((bDeathmatchSettings&Revive), 2);
	bSet[5]=BoolToString((bDeathmatchSettings&FriendlyFire), 2);
	bSet[6]=BoolToString((bDeathmatchSettings&MobSpawnUnit), 2);
	bSet[7]=BoolToString((bDeathmatchSettings&EquipmentUsage), 2);
	bSet[8]=BoolToString((bDeathmatchSettings&GearItemUsage), 2);
	bSet[9]=BoolToString((bDeathmatchSettings&EqualWeapons), 2);
	bSet[10]=BoolToString((bDeathmatchSettings&TeamTalk), 2);
	bSet[11]=BoolToString((bDeathmatchSettings&TeamBalance), 2);

	format(StdSettings, 76, "\
	Max Players:\t\t\t\t%d\n\
	Min Players:\t\t\t\t%d\n\
	Score Limit:\t\t\t\t%d\n\
	Time Limit:\t\t\t\t%d\n", DMmaxP, DMminP, ScoreLim, MatchTimeLimit);

	format(BoolSettings, 247, "\
	Hardcore:\t\t\t\t%s\n\
	Arcade Mode:\t\t\t\t%s\n\
	Vehicles:\t\t\t\t%s\n\
	Headshot Instant Kill:\t\t\t%s\n\
	Reviving Players\t\t\t%s\n\
	Friendly Fire\t\t\t\t%s\n\
	MSU (Conquest)\t\t\t%s\n\
	Equipment Usage\t\t\t%s\n\
	Gear Items\t\t\t\t%s\n\
	Equal Weapons\t\t\t\t%s\n\
	Team Talk\t\t\t\t%s\n\
	Team Balance\t\t\t\t%s\n", bSet[0], bSet[1], bSet[2], bSet[3], bSet[4], bSet[5], bSet[6], bSet[7], bSet[8], bSet[9], bSet[10], bSet[11]);

	format(OtherOptions, 50, "\
	Start Deathmatch\n\
	Cancel Deathmatch\n\
	Reset Settings");

	format(FullString, 372, "%s%s%s", StdSettings, BoolSettings, OtherOptions);
	ShowPlayerDialog(playerid, d_Settings, DIALOG_STYLE_LIST, "Deathmatch Settings", FullString, "Change", "Info");
}
FormatSpawnMenu(playerid)
{
	new str[46], endstr[64];
	format(str, 46, "%s\n%s\n%s\n%s", CPname[0], CPname[1], CPname[2], CPname[3]);
	if(bDeathmatchSettings&MobSpawnUnit)format(endstr, 150, "%s\nMobile Spawn Unit", str);
	else endstr=str;
	ShowPlayerDialog(playerid, d_Spawnpoint, DIALOG_STYLE_LIST, "Choose Spawn Point", endstr, "View", "Accept");
}
FormatKitInfo(playerid)
{
	new
		KitInfo_1[200],
		KitInfo_2[200],
		KitInfo_3[200],
		KitInfo_4[200],
		KitInfoStr[800],
		tmpRank = pRank(playerid);

	format(KitInfo_1, 200,
	"Assault:\n\
	\tPrimary:\t"#C_YELLOW"%s"#C_WHITE"\n\
	\tSecodary:\t"#C_GREEN"%s"#C_WHITE"\n\
	\tThrown:\t"#C_ORANGE"%s"#C_WHITE"\n\
	\tEquipment:\t"#C_BLUE"Supply"#C_WHITE"\n\n",
	WepData[RankWeapons[0][tmpRank][1]][WepName], WepData[RankWeapons[0][tmpRank][0]][WepName], WepData[RankWeapons[0][tmpRank][2]][WepName]);

	format(KitInfo_2, 200,
	"Medic:\n\
	\tPrimary:\t"#C_YELLOW"%s"#C_WHITE"\n\
	\tSecodary:\t"#C_GREEN"%s"#C_WHITE"\n\
	\tThrown:\t"#C_ORANGE"%s"#C_WHITE"\n\
	\tEquipment:\t"#C_BLUE"Medkit"#C_WHITE"\n\n",
	WepData[RankWeapons[1][tmpRank][1]][WepName], WepData[RankWeapons[1][tmpRank][0]][WepName], WepData[RankWeapons[1][tmpRank][2]][WepName]);

	format(KitInfo_3, 200,
	"Sniper:\n\
	\tPrimary:\t"#C_YELLOW"%s"#C_WHITE"\n\
	\tSecodary:\t"#C_GREEN"%s"#C_WHITE"\n\
	\tThrown:\t"#C_ORANGE"%s"#C_WHITE"\n\
	\tEquipment:\t"#C_BLUE"Mines"#C_WHITE"\n\n",
	WepData[RankWeapons[2][tmpRank][1]][WepName], WepData[RankWeapons[2][tmpRank][0]][WepName], WepData[RankWeapons[2][tmpRank][2]][WepName]);

	format(KitInfo_4, 200,
	"Engineer:\n\
	\tPrimary:\t"#C_YELLOW"%s"#C_WHITE"\n\
	\tSecodary:\t"#C_GREEN"%s"#C_WHITE"\n\
	\tThrown:\t"#C_ORANGE"%s"#C_WHITE"\n\
	\tEquipment:\t"#C_BLUE"Repair"#C_WHITE"\n",
	WepData[RankWeapons[3][tmpRank][1]][WepName], WepData[RankWeapons[3][tmpRank][0]][WepName], WepData[RankWeapons[3][tmpRank][2]][WepName]);

	format(KitInfoStr, 800, "%s\n%s\n%s\n%s", KitInfo_1, KitInfo_2, KitInfo_3, KitInfo_4);

	ShowPlayerDialog(playerid, d_KitInfo, DIALOG_STYLE_MSGBOX, "Kits", KitInfoStr, "Close", "");
}
FormatGearMenu(playerid)
{
	new
	    info[64],
		list[200];

	format(info, 64, "You are currently using "#C_YELLOW"%s", GearName[pGear(playerid)]);
	for(new i=0;i<sizeof(GearName);i++)format(list, 200, "%s\n%s", list, GearName[i]);
    ShowPlayerDialog(playerid, d_Gearselect, DIALOG_STYLE_LIST, info, list, "Accept", "Info");
}
GivePlayerKitWeapons(playerid, crate=0)
{
	new tmpRank=pRank(playerid),AmmoMultiplier=1;
	if(bDeathmatchSettings&GearItemUsage&&pGear(playerid)==g_ExtraMags)AmmoMultiplier=2;
	if(bDeathmatchSettings&EqualWeapons || bDeathmatchSettings&ArcadeMode)tmpRank=15;
	ResetPlayerWeapons(playerid);
	GivePlayerWeapon(playerid, RankWeapons[pKit(playerid)][tmpRank][2], RankWeapons[pKit(playerid)][tmpRank][5]);
	GivePlayerWeapon(playerid, RankWeapons[pKit(playerid)][tmpRank][0], RankWeapons[pKit(playerid)][tmpRank][3]*AmmoMultiplier);
	if(pGear(playerid)==g_Rocket)GivePlayerWeapon(playerid, Rpg, 1);
	else GivePlayerWeapon(playerid, RankWeapons[pKit(playerid)][tmpRank][1], RankWeapons[pKit(playerid)][tmpRank][4]*AmmoMultiplier);

	if(bDeathmatchSettings&EquipmentUsage)
	{
		switch(pKit(playerid))
		{
		    case 0:if(crate==0)TotalSupplies[playerid] = 1;
		    case 1:TotalHeal[playerid] = 1;
		    case 2:
			{
				if(bDeathmatchSettings&GearItemUsage && pGear(playerid)==g_ExtraMines)TotalMines[playerid]=4;
				else TotalMines[playerid]=2;
			}
		    case 3:TotalRepair[playerid] = 1;
		}
	}
	UpdateEqipmentText(playerid);
}
SetupSpawnPoint(playerid)
{
	if(DMmode!=DM_MODE_CQS)
	{
		new t=pTeam(playerid);
		if(DMmap==-2) for(new i;i<3;i++)pSpawnPoint[playerid][i]=CustomSpawns[t][i];
		else for(new i;i<3;i++)pSpawnPoint[playerid][i]=SpawnPositions[MapSpawnSide[t]][i];
	}
	Streamer_Update(playerid);
}
forward BleedOut(id);

SetPlayerToSpectate(playerid, toggle)
{
	if(!toggle)
	{
	    TogglePlayerSpectating(playerid, false);
	    PlayerSpectateTarget[playerid]=-1;
	    return 1;
	}
	new tmpID;
	for(tmpID=0;tmpID<MAX_PLAYERS;tmpID++)
	{
	    if( (IsPlayerConnected(tmpID)) && (bPlayerGameSettings[tmpID]&InDM) && (bPlayerGameSettings[tmpID]&Spawned) )
	    {
	        PlayerSpectateTarget[playerid]=tmpID;
	        TogglePlayerSpectating(playerid, true);
	        PlayerSpectatePlayer(playerid, tmpID);
	        return 1;
	    }
	}
	return 0;
}

stock Spectate_Next(playerid)
{
	new tmpID;
	while( (!IsPlayerConnected(tmpID)) && !(bPlayerGameSettings[tmpID]&InDM) && !(bPlayerGameSettings[tmpID]&Spawned) )
	{
	    if( tmpID==(MAX_PLAYERS-1) )tmpID=0;
	    if( tmpID==PlayerSpectateTarget[playerid] )return 0;
	    tmpID++;
	}
	PlayerSpectateTarget[playerid]=tmpID;
	PlayerSpectatePlayer(playerid, tmpID);
	return 1;
}
stock Spectate_Prev(playerid)
{
	new tmpID;
	while( (!IsPlayerConnected(tmpID)) && !(bPlayerGameSettings[tmpID]&InDM) && !(bPlayerGameSettings[tmpID]&Spawned) )
	{
	    if(tmpID==0)tmpID=(MAX_PLAYERS-1);
	    if(tmpID==PlayerSpectateTarget[playerid] )return 0;
	    tmpID--;
	}
	PlayerSpectateTarget[playerid]=tmpID;
	PlayerSpectatePlayer(playerid, tmpID);
	return 1;
}


LoadDeathmatch()
{
	DMmode_tmp=DMmode;
	bitFalse(bServerGlobalSettings, DMstarted);
	bitTrue(bServerGlobalSettings, DMInProgress);
	MapSpawnSide[0]=random(1);
	MapSpawnSide[1]=!MapSpawnSide[0];

	SetGameModeText(ModeNames[DMmode]);

	static dmFile[50];
	format(dmFile, 50, dmDataFile, DMmap, MapNames[DMmap]);

	if(DMmap==-1)SetMapName("Custom Created DM");
	else
	{
		SetMapName(MapNames[DMmap]);
		if(!fexist(dmFile))return printf("File %s Not Found", dmFile);
		else file_Open(dmFile);
		sscanf(file_GetStr(GEN_FileDataKeys[0]), "p<,>ffffff", DMCamPos[0], DMCamPos[1], DMCamPos[2], DMCamPos[3], DMCamPos[4], DMCamPos[5]);
		DMweather = file_GetVal(GEN_FileDataKeys[1]);
		sscanf(file_GetStr(GEN_FileDataKeys[2]), "p<,>dd", DMtime_H, DMtime_M);
		sscanf(file_GetStr(GEN_FileDataKeys[3]), "s[10]", MapAuthor);
		sscanf(file_GetStr(GEN_FileDataKeys[4]), "p<,>fff", SpawnPositions[0][0], SpawnPositions[0][1], SpawnPositions[0][2]);
		sscanf(file_GetStr(GEN_FileDataKeys[5]), "p<,>fff", SpawnPositions[1][0], SpawnPositions[1][1], SpawnPositions[1][2]);
		sscanf(file_GetStr(GEN_FileDataKeys[6]), "s[128]", MapInfo_Bio);
		sscanf(file_GetStr(GEN_FileDataKeys[7]), "s[32]", MapInfo_Size);
		sscanf(file_GetStr(GEN_FileDataKeys[8]), "s[32]", MapInfo_Kit);

		if(file_IsKey(GEN_FileDataKeys[6]))
		{
			sscanf(file_GetStr(GEN_FileDataKeys[6]), "ffff", DMzoneP[0], DMzoneP[1], DMzoneP[2], DMzoneP[3]);
			DMzone=CreateDynamicRectangle(DMzoneP[0], DMzoneP[1], DMzoneP[2], DMzoneP[3], DEATHMATCH_WORLD);
		}
		LoadDM();
		file_Close();
	}
	if(DMmode==DM_MODE_TDM)SetGameModeText("Team Deathmatch");
	if(DMmode==DM_MODE_AD)
	{
	    file_Open(dmFile);
		DefendingTeam = file_GetVal(AD_FileDataKeys[0]);
		MaxPoints=1;
		sscanf(file_GetStr(AD_FileDataKeys[1]), "p<,>fff", CapturePoint[0][0], CapturePoint[0][1], CapturePoint[0][2]);
		if(file_IsKey(AD_FileDataKeys[2]))
		{
			sscanf(file_GetStr(AD_FileDataKeys[2]), "p<,>fff", CapturePoint[1][0], CapturePoint[1][1], CapturePoint[1][2]);
			MaxPoints=2;
		}
		if(file_IsKey(AD_FileDataKeys[3]))
		{
			sscanf(file_GetStr(AD_FileDataKeys[3]), "p<,>fff", CapturePoint[2][0], CapturePoint[2][1], CapturePoint[2][2]);
			MaxPoints=3;
		}
        file_Close();

		PointToCapture		=	CreateDynamicSphere(CapturePoint[0][0], CapturePoint[0][1], CapturePoint[0][2], 5.0, DEATHMATCH_WORLD);
		ADbar				=	CreateProgressBar(50, 200, 60, 5, YELLOW, ADcaptureTime);
		ADfill				=	0;
		CaptureProgress 	=	0;
		CaptureIcon			=	CreateDynamicMapIcon(CapturePoint[CaptureProgress][0], CapturePoint[CaptureProgress][1], CapturePoint[CaptureProgress][2], 19, BLUE, DEATHMATCH_WORLD, _, _, 1000.0);
		SetGameModeText("Attack/Defend");
	}
	if(DMmode==DM_MODE_CTF)
	{
	    file_Open(dmFile);
		sscanf(file_GetStr(CTF_FileDataKeys[0]), "p<,>fff", CtfPosF[0][0], CtfPosF[0][1], CtfPosF[0][2]);
		sscanf(file_GetStr(CTF_FileDataKeys[1]), "p<,>fff", CtfPosF[1][0], CtfPosF[1][1], CtfPosF[1][2]);
        file_Close();

		CtfFlag[0] = CreateDynamicPickup(CTF_FLAG_MODEL, 1, CtfPosF[0][0], CtfPosF[0][1], CtfPosF[0][2], DEATHMATCH_WORLD, _, _, 300.0);
		CtfFlag[1] = CreateDynamicPickup(CTF_FLAG_MODEL, 1, CtfPosF[1][0], CtfPosF[1][1], CtfPosF[1][2], DEATHMATCH_WORLD, _, _, 300.0);

		SetGameModeText("Capture The Flag");
	}
	if(DMmode==DM_MODE_CQS)
	{
		file_Open(dmFile);
		for(new cp;cp<MAX_CP;cp++)
		{
			sscanf(file_GetStr(CQS_FileDataKeys[cp]), "p<,>fff", CPpoint[cp][0], CPpoint[cp][1], CPpoint[cp][2]);
			format(CPname[cp], MAX_CPNAME, file_GetStr(CQS_FileDataKeys[cp+4]));
			sscanf(file_GetStr(CQS_FileDataKeys[cp+8]), "p<,>fff", CPOfSet[cp][0], CPOfSet[cp][1], CPOfSet[cp][2]);
			CPowner[cp]=file_GetVal(CQS_FileDataKeys[cp+12]);

			CPflag[cp]	= CreateDynamicSphere(CPpoint[cp][0], CPpoint[cp][1], CPpoint[cp][2], 10.0, DEATHMATCH_WORLD);
			CPbar[cp]	= CreateProgressBar(50, 200, 60, 5, BLUE, 20);
			CPfill[cp]	= 0;
			for(new t;t<2;t++)CPlabel[cp][t] = CreateDynamic3DTextLabel("<COMMAND POST>", YELLOW, CPpoint[cp][0], CPpoint[cp][1], CPpoint[cp][2], 1000.0, _, DEATHMATCH_WORLD);
		}
        file_Close();
		MatchTimeLimit=0;
		SetGameModeText("Conquest");
	}
	file_Close();
	TeamScore[Score][0] = 0;
	TeamScore[Score][1] = 0;
	TeamScore[Flags][0] = 0;
	TeamScore[Flags][1] = 0;
	TeamScore[Ticket][0] = 100;
	TeamScore[Ticket][1] = 100;
	TeamScoreUpdate();
	return 1;
}
StartDM()
{
	PlayerLoop(i)if(bPlayerGameSettings[i]&InLobby&&bPlayerGameSettings[i]&ReadyForDM)DMspawn(i);
	bitFalse(bServerGlobalSettings, LobbyCountingDown);
	TextDrawHideForAll(LobbyText);
	bitTrue(bServerGlobalSettings, DMstarted);
	if(MatchTimeLimit>0)MatchTime(MatchTimeLimit, 0);
}


JoinDeathMatch(playerid)
{
	bitTrue(bPlayerGameSettings[playerid], InLobby);
	bitFalse(bPlayerGameSettings[playerid], InDM);
	bitFalse(bPlayerGameSettings[playerid], ReadyForDM);
	bitFalse(bPlayerGameSettings[playerid], Spawned);
	pKit(playerid) = 0;
	bitTrue(pGear(playerid), g_ProxDet);
	if(GetPlayersInTeam(0)>GetPlayersInTeam(1))pTeam(playerid)=1;
	else pTeam(playerid)=0;

	if(DMmode==DM_MODE_CQS)
	{
		for(new cp=0;cp<MAX_CP;cp++)
		{
			if(CPowner[cp]==pTeam(playerid))
			{
				pSpawnPoint[playerid][0]=CPpoint[cp][0],
				pSpawnPoint[playerid][1]=CPpoint[cp][1],
				pSpawnPoint[playerid][2]=CPpoint[cp][2];
			}
		}
	}

	SetPlayerVirtualWorld(playerid, DEATHMATCH_WORLD);
	GangZoneShowForPlayer(playerid, JamZone, 0x000000FF);
	TogglePlayerControllable(playerid, 0);

	pDM_Data[playerid][PreKills]	= pKills(playerid);
	pDM_Data[playerid][PreDeaths]	= pDeaths(playerid);
	pDM_Data[playerid][PreExp]		= pExp(playerid);

	JoinLobby(playerid);
	
	UpdatePlayerIcons(playerid);
	
}

public JoinLobby(playerid)
{
	bitTrue(bPlayerGameSettings[playerid], InLobby);
	bitFalse(bPlayerGameSettings[playerid], ReadyForDM);

	HideMsgBox(playerid);
	SpecDM(playerid);
	TextDrawHideForPlayer(playerid, SpawnCount);
    if(!(bServerGlobalSettings&DMstarted) && !(bServerGlobalSettings&LobbyCountingDown))
	{
        UpdateLobbyCount();
		TextDrawShowForPlayer(playerid, LobbyText);
	}

	FormatLobbyInfoForAll();
	ShowMenuForPlayer(LobbyMenu, playerid);
	SetPlayerHP(playerid, GlobalMaxHP);

	HideHUD(playerid);

	Streamer_Update(playerid);
}
JoinQueue(playerid)
{
	bitTrue(bPlayerGameSettings[playerid], InLobby);
	bitTrue(bPlayerGameSettings[playerid], ReadyForDM);
	FormatLobbyInfo(playerid);

    if(bServerGlobalSettings&DMstarted)TextDrawShowForPlayer(playerid, SpawnCount);
    else TextDrawShowForPlayer(playerid, LobbyText);

	SpecDM(playerid);
	HideMenuForPlayer(LobbyMenu, playerid);
	HideHUD(playerid);
	Streamer_Update(playerid);
}
UpdateLobbyCount()
{
	new str[70];
	format(str, 70, "%d Players In Lobby~n~Type /joindm to join~n~", GetPlayersInLobby());
	TextDrawSetString(LobbyText, str);
}
UpdateQueueCountDown()
{
	new lobbycountstr[100];
	format(lobbycountstr, 100, "%d Players In Lobby~n~Type /joindm to join~n~Deathmatch Starting In %02d",  GetPlayersInLobby(), LobbyCountInt);
	TextDrawSetString(LobbyText, lobbycountstr);
	TextDrawShowForAll(LobbyText);
	if(LobbyCountInt<=0)StartDM();
	LobbyCountInt--;
}
ExitDeathmatch(playerid)
{
	ResetPlayerWeapons(playerid);

	HideHUD(playerid);
	UpdatePlayerIcons(playerid);

	TextDrawHideForPlayer(playerid, HealthCount[playerid]);
	TextDrawHideForPlayer(playerid, LobbyText);
	TextDrawHideForPlayer(playerid, SpawnCount);

	TextDrawShowForPlayer(playerid, infobar);
	TextDrawShowForPlayer(playerid, ClockText);

	GangZoneHideForPlayer(playerid, JamZone);
	HideMenuForPlayer(LobbyMenu, playerid);
	HideMsgBox(playerid);

	RemovePlayerAttachedObject(playerid, PRIMARY_SLOT);
	RemovePlayerAttachedObject(playerid, SIDEARM_SLOT);

	SetPlayerPos(playerid, 2268.9895,1518.6492,42.8156);
	SetPlayerSkin(playerid, pSkin(playerid));
	SetSpawnInfo(playerid, -1, pSkin(playerid), 2268.9895,1518.6492,42.8156,271.1070, 0, 0, 0, 0, 0, 0);
	SetPlayerWorldBounds(playerid, 20000.0, -20000.0, 20000.0, -20000.0);
	SetPlayerVirtualWorld(playerid, FREEROAM_WORLD);
	SetPlayerInterior(playerid, 0);
	SetCameraBehindPlayer(playerid);
	TogglePlayerControllable(playerid, true);
	PlayerLoop(i)
	{
		ShowPlayerNameTagForPlayer	(playerid, i, true);
		ShowPlayerNameTagForPlayer	(i, playerid, true);
		SetPlayerColor(playerid, cArray[pColour(playerid)][colour_hex]);
	}
	pTeam(playerid) = -1;
	SetPlayerTeam(playerid, -1);
	bitFalse(bPlayerGameSettings[playerid], InDM);
	bitFalse(bPlayerGameSettings[playerid], InLobby);
	bitFalse(bPlayerGameSettings[playerid], ReadyForDM);
	SetPlayerScore(playerid, 0);
	if(DMmode_tmp == DM_MODE_AD)
	{
	}
	if(DMmode_tmp == DM_MODE_CTF)
	{
	}
	if(DMmode_tmp == DM_MODE_CQS)for(new cp;cp<MAX_CP;cp++)RemovePlayerMapIcon(playerid, CPicon[cp][pTeam(playerid)]);

    if(!(bServerGlobalSettings&DMstarted) && !(bServerGlobalSettings&LobbyCountingDown))UpdateLobbyCount();
	if( (bServerGlobalSettings&DMInProgress) && (GetPlayersInDM()==0&&GetPlayersInLobby()==0) )EndDeathmatch();
}

ShowHUD(playerid)
{
	TextDrawShowForPlayer(playerid, HealthCount[playerid]);
	TextDrawShowForPlayer(playerid, ScoreBox);
	if(MatchTimeLimit>0)TextDrawShowForPlayer(playerid, MatchTimeCounter);
	TextDrawShowForPlayer(playerid, SpecialWeps[playerid]);
	ShowProgressBarForPlayer(playerid, XPbar[playerid]);
}
HideHUD(playerid)
{
	TextDrawHideForPlayer(playerid, ScoreBox);
	TextDrawHideForPlayer(playerid, MatchTimeCounter);
	TextDrawHideForPlayer(playerid, SpecialWeps[playerid]);
	TextDrawHideForPlayer(playerid, ScoreStatus_Winning);
	TextDrawHideForPlayer(playerid, ScoreStatus_Tie);
	TextDrawHideForPlayer(playerid, ScoreStatus_Losing);
	HideProgressBarForPlayer(playerid, XPbar[playerid]);
}


UpdateScoreStatus(playerid=-1)
{
	new
		iaScore[2],
		iLeadTeam;

	if(DMmode==DM_MODE_TDM)
	{
	    iaScore[0]=TeamScore[Score][0];
	    iaScore[1]=TeamScore[Score][1];
	}
	if(DMmode==DM_MODE_CTF)
	{
	    iaScore[0]=TeamScore[Flags][0];
	    iaScore[1]=TeamScore[Flags][1];
	}
	if(DMmode==DM_MODE_CQS)
	{
	    iaScore[0]=TeamScore[Ticket][0];
	    iaScore[1]=TeamScore[Ticket][1];
	}

/*
	if(iaScore[0] > iaScore[1])iLeadTeam=0;
	else iLeadTeam=1;
*/

	if(iaScore[0] == iaScore[1])
	{
		SetScoreStatus(0, 0, playerid);
		SetScoreStatus(1, 0, playerid);
	}
	else
	{
		while(iaScore[iLeadTeam] < iaScore[!iLeadTeam])iLeadTeam=!iLeadTeam;
		SetScoreStatus(iLeadTeam, 2, playerid);
		SetScoreStatus(!iLeadTeam, 1, playerid);
	}
}

SetScoreStatus(team, status, playerid)
{
	if(playerid!=-1)
	{
	    TextDrawHideForPlayer(playerid, ScoreStatus_Tie);
		TextDrawHideForPlayer(playerid, ScoreStatus_Losing);
		TextDrawHideForPlayer(playerid, ScoreStatus_Winning);
		if(status==0)TextDrawShowForPlayer(playerid, ScoreStatus_Tie);
		if(status==1)TextDrawShowForPlayer(playerid, ScoreStatus_Losing);
		if(status==2)TextDrawShowForPlayer(playerid, ScoreStatus_Winning);
		return 1;
	}
	PlayerLoop(i)
	{
	    if(pTeam(i)==team && bPlayerGameSettings[i]&Spawned)
	    {
			TextDrawHideForPlayer(i, ScoreStatus_Tie);
			TextDrawHideForPlayer(i, ScoreStatus_Losing);
			TextDrawHideForPlayer(i, ScoreStatus_Winning);
	        if(status==0)TextDrawShowForPlayer(i, ScoreStatus_Tie);
	        if(status==1)TextDrawShowForPlayer(i, ScoreStatus_Losing);
	        if(status==2)TextDrawShowForPlayer(i, ScoreStatus_Winning);
	    }
	}
	return 0;
}

LoadDM()
{
	LoadDM_Map(DMmap);
	LoadDM_Crates();
	LoadDM_Extras();
	if(bDeathmatchSettings&Vehicles)LoadDM_Vehicles();
    if(DMmode==DM_MODE_CQS&&(bDeathmatchSettings&MobSpawnUnit))
    {
        new Model, Float:X, Float:Y, Float:Z, Float:R;
        if(!file_IsKey(CQS_FileDataKeys[13]))print("Error Loading MSU Data");
		sscanf(file_GetStr(CQS_FileDataKeys[13]), "p<,>dffff", Model, X, Y, Z, R);
		MSU_VehicleID[0]=CreateVehicle(Model, X, Y, Z, R, -1, -1, 10000);
		sscanf(file_GetStr(CQS_FileDataKeys[14]), "p<,>dffff", Model, X, Y, Z, R);
		MSU_VehicleID[1]=CreateVehicle(Model, X, Y, Z, R, -1, -1, 10000);
    }
	if(bDeathmatchSettings&MobSpawnUnit)for(new v;v<2;v++)SetVehicleVirtualWorld(MSU_VehicleID[v], DEATHMATCH_WORLD);
}
LoadDM_Map(mapid)
{
    new File:file, fname[50], line[90], modelid, Float:px, Float:py, Float:pz, Float:rx, Float:ry, Float:rz, linecount=1;
    format(fname, 50, dmMapFile, mapid, MapNames[mapid]);
    file=fopen(fname, io_read);
    if(!file)return printf("File %s Not Found", fname);
    while(fread(file, line))
    {
		if(sscanf(line, "p<,>dffffff", modelid, px, py, pz, rx, ry, rz))printf("Error in file %s on line: %d objid: %d modelid: %d", fname, linecount, TotalDMObjects, modelid);
		CreateDynamicObject(modelid, px, py, pz, rx, ry, rz, DEATHMATCH_WORLD, _, _, MAX_RENDER_DISTANCE);
		TotalDMObjects++;
        linecount++;
    }
	printf("Deathmatch Map Loaded: %d Object Count: %d", mapid, TotalDMObjects);
	return 1;
}
LoadDM_Crates()
{
	new FileStr[64];
	format(FileStr, 64, dmCrtFile, DMmap, MapNames[DMmap]);
	if(!fexist(FileStr))return print("Error: Deathmatch Crate File Not Found");
	new
		File:File,
		line[128],
		Float:x,
		Float:y,
		Float:z,
		Float:r;

	File=fopen(FileStr, io_read);
	while(fread(File, line))
	{
		if(!sscanf(line, "p<,>fffF(0.0)", x, y, z, r))AddSupplyCrate(x, y, z, r);
		else print("Error: Deathmatch Crate File");
	}
	fclose(File);
	return 1;
}
LoadDM_Vehicles()
{
	new vFileStr[64];
	format(vFileStr, 64, dmVehFile, DMmap, MapNames[DMmap]);
	if(!fexist(vFileStr))return 0;
	new
		File:vFile,
		line[128],
		modelid,
		Float:x,
		Float:y,
		Float:z,
		Float:r;

	vFile=fopen(vFileStr, io_read);
	while(fread(vFile, line))
	{
		if(!sscanf(line, "p<,>dffff", modelid, x, y, z, r))SetVehicleVirtualWorld(CreateVehicle(modelid, x, y, z, r, -1, -1, 10000), DEATHMATCH_WORLD);
		else print("Error: Deathmatch Vehicle File");
	}
	fclose(vFile);
	return 1;
}
LoadDM_Extras()
{
	if(DMmap==2)
	{
		if(DMmode==DM_MODE_CTF)
		{
			MoveDynamicObject(armygate, 96.886208, 1922.040039, 17.310095, 1.0);
			BaseLockdown = 1;
		}
	}
}

SpecDM(playerid)
{
	SetPlayerVirtualWorld(playerid, DEATHMATCH_WORLD);
	TogglePlayerControllable(playerid, 0);
	if(DMmode==DM_MODE_CQS)
	{
	    for(new cp;cp<MAX_CP;cp++)
	    {
		    if(CPowner[cp]==pTeam(playerid))
		    {
				SetPlayerCameraPos(playerid,	CPOfSet[cp][0], CPOfSet[cp][1], CPOfSet[cp][2]);
				SetPlayerCameraLookAt(playerid,	CPpoint[cp][0], CPpoint[cp][1], CPpoint[cp][2]);
				SetPlayerPos(playerid,			CPpoint[cp][0], CPpoint[cp][1], CPpoint[cp][2]-2.0);
				break;
			}
		}
	}
	else
	{
		if(DMmap==-2)SetCameraBehindPlayer(playerid);
		else
		{
			SetPlayerCameraPos(playerid,	DMCamPos[0], DMCamPos[1], DMCamPos[2]);
			SetPlayerCameraLookAt(playerid,	DMCamPos[3], DMCamPos[4], DMCamPos[5]);
			SetPlayerPos(playerid,			DMCamPos[3], DMCamPos[4], DMCamPos[5]-2.0);
		}
	}
	Streamer_Update(playerid);
}
DMspawn(playerid)
{
	if(bPlayerGameSettings[playerid]&GodMode)bitFalse(bPlayerGameSettings[playerid], GodMode);
	bitTrue(bPlayerGameSettings[playerid], Spawned);

	// HUD
	TextDrawHideForPlayer(playerid, LobbyText);
	TextDrawHideForPlayer(playerid, SpawnCount);
	TextDrawHideForPlayer(playerid, infobar);
	TextDrawHideForPlayer(playerid, ClockText);
	ShowHUD(playerid);
	UpdateHealthBar(playerid);
	HideMsgBox(playerid);
	UpdatePlayerIcons(playerid);
	UpdateScoreStatus(playerid);

	if(bDeathmatchSettings&GearItemUsage)
	{
		if(pGear(playerid)==g_Night)GivePlayerWeapon(playerid, Nightvision, 1);
		if(pGear(playerid)==g_Thermal)GivePlayerWeapon(playerid, Thermalvision, 1);
	}
	SetPlayerToTeam(playerid, pTeam(playerid));

	SetPlayerVirtualWorld(playerid, DEATHMATCH_WORLD);
	SetCameraBehindPlayer(playerid);
	SetPlayerArmour(playerid, 0.0);
	SetPlayerHP(playerid, GlobalMaxHP);
	ResetPlayerWeapons(playerid);
	TogCon(1000,playerid);

	bitTrue(bPlayerGameSettings[playerid], InDM);
	bitFalse(bPlayerGameSettings[playerid], InLobby);
	bitFalse(bPlayerGameSettings[playerid], ReadyForDM);
	bitFalse(bPlayerGameSettings[playerid], FirstSpawn);

	bitTrue(bPlayerDeathmatchSettings[playerid], GearUse);
	UpdatePlayerXPBar(playerid);

	UpdateEqipmentText(playerid);


	if(DMmode==DM_MODE_TDM)TextDrawShowForPlayer(playerid, ScoreBox);
	else if(DMmode==DM_MODE_AD)
	{
		pSpawnPoint[playerid][0]=CapturePoint[CaptureProgress][0],pSpawnPoint[playerid][1]=CapturePoint[CaptureProgress][1],pSpawnPoint[playerid][2]=CapturePoint[CaptureProgress][2];
	}
	else if(DMmode==DM_MODE_CTF)
	{
		TextDrawShowForPlayer(playerid, ScoreBox);
		bitFalse(bPlayerDeathmatchSettings[playerid], HasFlag);
		UpdateFlagIcons();
	}
	else if(DMmode==DM_MODE_CQS)
	{
		TextDrawShowForPlayer(playerid, ScoreBox);
		UpdateCPIconsForPlayer(playerid);
	}

	if(bDeathmatchSettings&Hardcore)SetPlayerHP(playerid, GlobalMaxHP/2);
	else SetPlayerHP(playerid, GlobalMaxHP);

	GivePlayerKitWeapons(playerid);

	if(DMmode!=DM_MODE_CQS)SetupSpawnPoint(playerid);
	SetPlayerPos(playerid, pSpawnPoint[playerid][0], pSpawnPoint[playerid][1], pSpawnPoint[playerid][2]+0.5);
	PreloadPlayerAnims(playerid);
	Streamer_Update(playerid);
}
EndRound()
{
	new TeamScores[2];

	SetTimer("EndDeathmatch", 10000, false);

	if(DMmode==DM_MODE_TDM)
	{
		TeamScores[0]=TeamScore[Score][0];
		TeamScores[1]=TeamScore[Score][1];
	}
	if(DMmode==DM_MODE_AD)
	{
		TeamScores[WinningTeam]=1;
		TeamScores[!WinningTeam]=0;
	}
	if(DMmode==DM_MODE_CTF)
	{
		TeamScores[0]=TeamScore[Flags][0];
		TeamScores[1]=TeamScore[Flags][1];
	}
	if(DMmode==DM_MODE_CQS)
	{
		TeamScores[WinningTeam]=1;
		TeamScores[!WinningTeam]=0;
	}

	if(TeamScores[0]>TeamScores[1])WinningTeam=0;
	if(TeamScores[0]<TeamScores[1])WinningTeam=1;
	if(TeamScores[0]==TeamScores[1])WinningTeam=-1;

	new playerScores[MAX_PLAYERS][rankingEnum], h_id;
	while(IsPlayerConnected(h_id))h_id++;
	LeaderBoard(playerScores, 0, h_id);

	PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)
	{
		SpecDM(i);

		msg(i, YELLOW, "- Match Stats");
		msgF(i, BLUE, "Most Kills: %s (%d)", GetName(MostKills()), pInfo[MostKills()][pI_Kills]-pDM_Data[MostKills()][PreKills]);
		msgF(i, BLUE, "Most Exp: %s (%d)", GetName(MostXP()), pInfo[MostXP()][pI_Exp]-pDM_Data[MostXP()][PreExp]);
		msgF(i, BLUE, "Most Deaths: %s (%d)", GetName(MostDeaths()), pInfo[MostDeaths()][pI_Deaths]-pDM_Data[MostDeaths()][PreDeaths]);
		msgF(i, LGREEN, "Your Stats: Exp Earned: %d - Kills: %d - Deaths: %d", pInfo[i][pI_Exp]-pDM_Data[i][PreExp], pInfo[i][pI_Kills]-pDM_Data[i][PreKills], pInfo[i][pI_Deaths]-pDM_Data[i][PreDeaths]);

		if(WinningTeam==pTeam(i))
		{
			GameTextForPlayer(i, "~n~~n~~b~Your team won!", 3000, 5);
			GiveXP(i, 30, "Winning");
		}
		if(WinningTeam==poTeam(i))
		{
			GameTextForPlayer(i, "~n~~n~~b~Your team lost!", 3000, 5);
			GiveXP(i, 10, "Taking Part");
		}
		if(WinningTeam==-1)
		{
			GameTextForPlayer(i, "~n~~n~~g~It was a draw", 3000, 5);
			GiveXP(i, 20, "Taking Part");
		}
		RankCheck(i);
		SaveDMStats(i);
	}
}
SaveDMStats(playerid)
{
	new pFile[40];
	pFile=GetFile(playerid);
	file_Open(pFile);
	{
		file_SetVal("xp", pExp(playerid));
		file_SetVal("tk", pInfo[playerid][pI_TeamKills]);
		file_SetVal("kills", pKills(playerid));
		file_SetVal("deaths", pDeaths(playerid));
		file_SetVal("headshots", pHeadShot(playerid));
		file_SetVal("killchain", pInfo[playerid][pI_HighStreak]);
		if(!file_IsKey("wins"))file_SetVal("wins", 0);
		if(!file_IsKey("losses"))file_SetVal("losses", 0);
		if(pTeam(playerid)==WinningTeam)file_IncVal("wins", 1);
		else file_IncVal("losses", 1);
	}
	file_Save(pFile);
	file_Close();
}
public EndDeathmatch()
{
	StopMatchTime();
	PlayerLoop(i)CapturingCP[i]=-1;
	for(new i=0;i<MAX_CP;i++)
	{
		CPowner[i]=-1;
		CPfill[i]=0;
	}
	SetGameModeText("Freeroam[NoDM]");
	SetMapName("Freeroam[NoDM]");
	PlayerLoop(i)
	{
		if(DMmode==DM_MODE_AD)
		{
		   	DestroyDynamicArea(PointToCapture);
		   	StopMatchTime();
			DestroyDynamicMapIcon(CaptureIcon);
			DestroyProgressBar(ADbar);
		}
		if(DMmode==DM_MODE_CTF)
		{
			DestroyDynamicPickup(CtfFlag[0]);
			DestroyDynamicPickup(CtfFlag[1]);
			RemovePlayerMapIcon(i, CtfIcon);
		}
		if(DMmode==DM_MODE_CQS)
		{
			for(new cp=0;cp<MAX_CP;cp++)
			{
				DestroyDynamicArea(CPflag[cp]);
				DestroyDynamic3DTextLabel(CPlabel[cp][0]);
				DestroyDynamic3DTextLabel(CPlabel[cp][1]);
				RemovePlayerMapIcon(i, CPicon[cp][0]);
				RemovePlayerMapIcon(i, CPicon[cp][1]);
				DestroyProgressBar(CPbar[cp]);
			}
		}
	}
	UnloadDM();
	ResetDMVariables();
	PlayerLoop(i)if(bPlayerGameSettings[i]&InDM)ExitDeathmatch(i);
}
UnloadDM()
{
	if(DMmap!=-1)UnloadDM_Map(DMmap);
	if(bDeathmatchSettings&Vehicles)for(new v;v<MAX_VEHICLES;v++)if(GetVehicleVirtualWorld(v)==DEATHMATCH_WORLD)DestroyVehicle(v);
}
UnloadDM_Map(mapid)
{
	new objCount = CountDynamicObjects()-1;
	for(new ID;ID<objCount;ID++)
	{
		if(Streamer_IsInArrayData(STREAMER_TYPE_OBJECT, ID, E_STREAMER_WORLD_ID, DEATHMATCH_WORLD))DestroyDynamicObject(ID);
	}
	printf("Deathmatch Map Unloaded: %d Object Count: %d", mapid, TotalDMObjects);
	TotalDMObjects=0;
}
ResetDMVariables()
{
	TeamScore[Score][0] = 0,
	TeamScore[Score][1] = 0,
	TeamScore[Flags][0] = 0,
	TeamScore[Flags][1] = 0,
	TeamScore[Ticket][0] = 100,
	TeamScore[Ticket][1] = 100,
	ScoreLimit			= 10,
	FlagLimit			= 10,
	ADfill				= 0,
	WinningTeam			= -1,

	MaxPoints=0,
	CaptureProgress=0;

	for(new i;i<3;i++)
	{
		CapturePoint[i][0]=0.0,
		CapturePoint[i][1]=0.0,
		CapturePoint[i][2]=0.0;

		CtfPosF[0][i]=0.0,
		CtfPosF[1][i]=0.0;
	}
	PointCT=false,
	capturer=FreeID,
	ADfill=0,
	ADcaptureTime=30;
	
	new iconIncID;
	for(new cp;cp<MAX_CP;cp++)
	{
		CPowner		[cp]=-1;
		CPpoint		[cp][0]=0.0;
		CPpoint		[cp][1]=0.0;
		CPpoint		[cp][2]=0.0;
		CPOfSet		[cp][0]=0.0;
		CPOfSet		[cp][1]=0.0;
		CPOfSet		[cp][2]=0.0;
		CPfill		[cp]=0;
		CPtimer		[cp]=false;
		FirstToCapture[cp]=-1;
		for(new t;t<2;t++)
		{
		    CPicon[cp][t]=iconIncID;
		    iconIncID++;
		}
	}

	DMhost=FreeID,
	DMmap=-1,
	DMmode=-1,
	MSUactive[0]=false,
	MSUactive[1]=false,
	DMzoneP[0]=0.0,
	DMzoneP[1]=0.0,
	DMzoneP[2]=0.0,
	DMzoneP[3]=0.0,
	DMweather=0,
	DMtime_H=0,
	DMtime_M=0,
	DMmode_tmp=-1;
	bitFalse(bServerGlobalSettings, DMInProgress);
	bitFalse(bServerGlobalSettings, DMstarted);

}
ResetDMSettings()
{
	DMmaxP=MAX_PLAYERS;
	DMminP=2;
	ScoreLimit=20;
	FlagLimit=5;
	TeamScore[Ticket][0]=100;
	TeamScore[Ticket][1]=100;
	MatchTimeLimit=10;
	LobbyCountInt=MAX_LOBBY_COUNT;

	bDeathmatchSettings = 0b100111011100;
}

//==============================================================================Deathmatch Commands

	CMD:startdm(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&DMbanned)msg(playerid, RED, "**You are banned from ALL deathmatches, try following the rules next time");
		else
		{
			if(bServerGlobalSettings&DMInProgress)msg(playerid, RED, "There is already a Deathmatch in progress");
			else
			{
			    if(!IsPlayerConnected(DMhost))DMhost=-1;
				if(DMhost == FreeID || DMhost == playerid)
				{
					ShowPlayerDialog(playerid, d_RegionSelect, DIALOG_STYLE_LIST, "Choose a map style category", RegionMenu, "Accept", "Info");
					TogglePlayerControllable(playerid, false);
					DMhost = playerid;
				}
				else if(DMhost != -1)msgF(playerid, BLUE, "%s is already starting a deathmatch", GetName(DMhost));
			}
		}
		return 1;
	}
	CMD:joindm(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&DMbanned)msg(playerid, RED, "**You are banned from ALL deathmatches, try following the rules next time");
		else
		{
			if((bServerGlobalSettings&DMInProgress) && !(bPlayerGameSettings[playerid]&InDM))
			{
			    if(GetPlayersInLobby()<=DMmaxP)
			    {
					JoinDeathMatch(playerid);
					if(bServerGlobalSettings&DMstarted)ShowMenuForPlayer(LobbyMenu, playerid);
					msgaF(ORANGE, "%s Has joined the Deathmatch, type /joindm to join", GetName(playerid));
				}
				else msg(playerid, RED, "Lobby Full");
			}
			if(bPlayerGameSettings[playerid]&InDM)msg(playerid, ORANGE, "You are already in the deathmatch, please /exitdm first. If you think there is a bug, use /bug or tell an admin.");
			if(!(bServerGlobalSettings&DMInProgress))msg(playerid, ORANGE, "There are no DMs in progress, you can host your own DM with /startdm");
		}
		return 1;
	}
	CMD:exitdm(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&InDM || bPlayerGameSettings[playerid]&InLobby || bPlayerGameSettings[playerid]&ReadyForDM)
		{
		    new pFile[40];
		    pFile=GetFile(playerid);
			file_Open(pFile);
			file_SetVal("xp", pDM_Data[playerid][PreExp]);
			file_Save(pFile);
			file_Close();
			msg(playerid, ORANGE, "**You have lost all your XP earned in this deathmatch");
			msgaF(0xFF00FFFF, "%s Exited Deathmatching and returned to the car park", GetName(playerid));
			SetPlayerPos(playerid, SpawnCams[rCpos][6], SpawnCams[rCpos][7], SpawnCams[rCpos][8]);
			SetPlayerSkin(playerid, pInfo[playerid][pI_Skin]);
			ExitDeathmatch(playerid);
		}
		return 1;
	}
	CMD:stopdm(playerid, params[])
	{
		if(bServerGlobalSettings&DMInProgress)
		{
			if( (DMhost == playerid) || (pAdmin(playerid) >= 4) )
			{
				PlayerLoop(i)
				{
					if( (bPlayerGameSettings[playerid]&InDM) || (bPlayerGameSettings[playerid]&InLobby) )
					{
						if(DMhost==playerid)			msg(i, ORANGE, "DM Ended by Host");
						else if(pAdmin(playerid) >= 4)	msg(i, YELLOW, "DM Ended by Admin");
					}
				}
				EndDeathmatch();
			}
			else msg(playerid, RED, "**You are not the DM host");
		}
		return 1;
	}
	CMD:mystats(playerid, params[])
	{
		new
			str[800],
			g_str[128],
			inveh_additional,
			onfoot_additional;

		if(EnterVehTick[playerid]==0)inveh_additional=0;
		else inveh_additional=(GetTickCount()-EnterVehTick[playerid]);
		if(EnterFootTick[playerid]==0)onfoot_additional=0;
		else onfoot_additional=(GetTickCount()-EnterFootTick[playerid]);

		new
			t_total=(pInfo[playerid][pI_TimePlayed]+(GetTickCount()-pInfo[playerid][pI_JoinTick])),
			t_session=(GetTickCount()-pInfo[playerid][pI_JoinTick]),
			t_inveh=(pInfo[playerid][pI_TimeInVeh]+inveh_additional),
			t_onfoot=(pInfo[playerid][pI_TimeOnFoot]+onfoot_additional);

		strcat(str, FormatColours("{WHITE}-  General\n"));
		format(g_str, 128, "{BLUE}Admin Level:\t\t\t{GREEN}%d\n", pAdmin(playerid));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Time Played (This Session):\t{GREEN}%s\n", TimeStamp(t_session));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Time Played (All Time):\t{GREEN}%s\n", TimeStamp(t_total));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Time In Vehicle:\t\t{GREEN}%s\n",TimeStamp(t_inveh));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Time On Foot:\t\t\t{GREEN}%s\n", TimeStamp(t_onfoot));
		strcat(str, FormatColours(g_str));

		strcat(str, FormatColours("\n\n{WHITE}-  Deathmatch\n"));
		format(g_str, 128, "{BLUE}Rank:\t\t\t\t{GREEN}%s(%d)\n", RankNames[pRank(playerid)], pRank(playerid));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Kills:\t\t\t\t{GREEN}%d\n", pKills(playerid));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Deaths:\t\t\t{GREEN}%d\n", pDeaths(playerid));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}XP:\t\t\t\t{GREEN}%d\n", pExp(playerid));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}Next Rank:\t\t\t{GREEN}%s(%d)\n", RankNames[pRank(playerid)+1], (pRank(playerid)+1));
		strcat(str, FormatColours(g_str));
		format(g_str, 128, "{BLUE}XP To Go:\t\t\t{GREEN}%d", (RequiredExp[pRank(playerid)+1]-pExp(playerid)));
		strcat(str, FormatColours(g_str));

		ShowPlayerDialog(playerid, d_Stats, DIALOG_STYLE_MSGBOX, "Your Stats", str, "Close", "");
		return 1;
	}
	CMD:raven(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&InDM)msg(playerid, GREEN, "Use the spawn menu when in a deathmatch");
		else
		{
			if(bServerGlobalSettings&FreeDM)
			{
				SetPlayerHP(playerid, 100.0);
				SetPlayerArmour(playerid, 0.0);
				SetPlayerToTeam(playerid, 0);
				ShowMenuForPlayer(KitSelect, playerid);

				msg(playerid, LGREEN, "Team: Raven, This is now your spawn point");
				msgaF(GREEN, "%s Has Joined The Raven Team", GetName(playerid));

				new Float:x, Float:y, Float:z, Float:rot;
				GetPlayerPos(playerid, x, y, z);
				GetPlayerFacingAngle(playerid, rot);
				SetSpawnInfo(playerid, 0, RavenSkins[pDM_Data[playerid][Kit]], x, y, z, rot, 0, 0, 0, 0, 0, 0);
			}
			else msg(playerid, RED, "Free For All Deathmatch mode is disabled, ask an online admin to enable it.");
		}
		return 1;
	}
	CMD:valor(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&InDM)msg(playerid, GREEN, "Use the spawn menu when in a deathmatch");
		else
		{
			if(bServerGlobalSettings&FreeDM)
			{
				SetPlayerHP(playerid, 100.0);
				SetPlayerArmour(playerid, 0.0);
				SetPlayerToTeam(playerid, 1);
				ShowMenuForPlayer(KitSelect, playerid);

				msg(playerid, LGREEN, "Team: Valor, This is now your spawn point");
				msgaF(GREEN, "%s Has Joined The Valor Team", GetName(playerid));

				new Float:x, Float:y, Float:z, Float:rot;
				GetPlayerPos(playerid, x, y, z);
				GetPlayerFacingAngle(playerid, rot);
				SetSpawnInfo(playerid, 1, ValorSkins[pDM_Data[playerid][Kit]], x, y, z, rot, 0, 0, 0, 0, 0, 0);
			}
			else msg(playerid, RED, "Free For All Deathmatch mode is disabled, ask an online admin to enable it.");
		}
		return 1;
	}
	CMD:free(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&InDM)msg(playerid, GREEN, "Use the spawn menu when in a deathmatch");
		else
		{
			if(bServerGlobalSettings&FreeDM)
			{
				SetPlayerHP(playerid, 100.0);
				SetPlayerArmour(playerid, 0.0);
				pTeam(playerid)=playerid+10;
				ShowMenuForPlayer(KitSelect, playerid);

				msg(playerid, LGREEN, "You have left your team, you are now fighting for yourself!");

				new Float:x, Float:y, Float:z, Float:rot;
				GetPlayerPos(playerid, x, y, z);
				GetPlayerFacingAngle(playerid, rot);
				SetSpawnInfo(playerid, playerid+10, pInfo[playerid][pI_Skin], x, y, z, rot, 0, 0, 0, 0, 0, 0);
			}
			else msg(playerid, RED, "Free For All Deathmatch mode is disabled, ask an online admin to enable it.");
		}
		return 1;
	}
	/*
	CMD:w(playerid, params[])
	{
		if(bPlayerGameSettings[playerid]&InDM)msg(playerid, RED, "Not allowed in DM");
		else
		{
			if(bServerGlobalSettings&CmdsDisable)msg(playerid, RED, "This command has been disabled by an admin");
			else
			{
				if(bServerGlobalSettings&FreeDM)GivePlayerKitWeapons(playerid);
				else msg(playerid, RED, "Free For All Deathmatch mode is disabled, ask an online admin to enable it.");
			}
		}
		return 1;
	}
	*/

